Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the quantity of the numbers in the both given permutations.  Next line contains n space-separated integers — the first permutation. Each number between 1 to n will appear in the permutation exactly once.  Next line describe the second permutation in the same format.

Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.

NoteIn the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.In the second sample, he removes number 5 and inserts it after 1.In the third sample, the sequence of changes are like this:  1 5 2 3 4 1 4 5 2 3 1 3 4 5 2 1 2 3 4 5  So he needs three moves.

<?php

$n=(int)fgets(STDIN);
$n++;
$a=trim(fgets(STDIN));
$a=preg_split("/ /",$a);
$b=trim(fgets(STDIN));
$b=preg_split('/ /',$b);
$ia=0;
$ib=0;
$total=0;
while ($ia<$n && $ib<$n-1){    //for sure if you have to go until the last one to find:it will be it...
      //echo $a[$ia]." ".$b[$ib].".\n";
      if ($a[$ia]==$b[$ib]){$ia++;$ib++;}
      else{
        $ib++;
        $total++;
      }
}
echo $total;

?>


Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains  distinct theorems. Besides, no theorem is mentioned in more than one card (that is,  theorems won't be mentioned in any card). During the exam several students may get the same card.We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 100) — the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 ≤ ai ≤ 100), the i-th number (1 ≤ i ≤ n) corresponds to Vasya's proficiency in the i-th theorem. The third line contains number q (0 ≤ q ≤ 100) — the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card:  integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).

Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.

NoteLet's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).The ⌊ x⌋ operation denotes taking integer part of real number x (rounding down).


When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.

The first line contains a single integer $$$n$$$ ($$$1 \leqslant n \leqslant 10^5$$$) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'. It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit $$$0$$$ or "one" which corresponds to the digit $$$1$$$.

Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.

NoteIn the first example, the correct initial ordering is "zero".In the second example, the correct initial ordering is "oneonezero".

<?php

function search($str) {
  // code goes here
  $num = '';
  $zero = preg_match_all("/[z]/", $str, $arr);
  $one = preg_match_all("/[n]/", $str, $arr);
  for($i =0; $i< $one;$i++){
    $num.= '1 ';
  }
  for($i =0; $i< $zero;$i++){
    $num.= '0 ';
  }
  return $num;
}

// keep this function call here
$file = fopen('php://stdin', 'r');
// $file = fopen('input.txt', 'r');
$line = fgets($file);
$str = fgets($file);
// $arr = explode(' ', $str);
echo search($str);
?>

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

$zeros = substr_count($s, "z");
$ones = substr_count($s, "n");

for ($i=0; $i<$ones; $i++) {
    echo "1 ";
}

for ($i=0; $i<$zeros; $i++) {
    echo "0 ";
}

?>

<?php
$d = intval(fgets(STDIN));
$v = fgets(STDIN);

echo str_repeat("1 ", substr_count($v, 'n')) . str_repeat("0 ", substr_count($v, 'z'));

<?php
$n=fgets(STDIN);
$input=fgets(STDIN);
$e=preg_match_all('/(e)/',$input);
$z=preg_match_all('/(z)/',$input);
$o=preg_match_all('/(o)/',$input);
$r=preg_match_all('/(r)/',$input);
$n=preg_match_all('/(n)/',$input);
$zero=0;
$one=0;
while($z != 0 or $e != 0 and $r != 0 and $o != 0){
      $z--;
      $e--;
      $r--;
      $o--;
      $zero++;
}
while($o != 0 or $e != 0 and $n != 0){
      $o--;
      $e--;
      $n--;
      $one+=1;
}
echo str_repeat('1 ',$one).str_repeat('0 ',$zero);


A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.

The first line contains a pair of integer numbers n and v (1 ≤ n ≤ 105; 1 ≤ v ≤ 109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti, pi (1 ≤ ti ≤ 2; 1 ≤ pi ≤ 104), where ti is the vehicle type (1 – a kayak, 2 – a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.

In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$e = array();
$f = array();
$i = array();
$j = array();
for($x = 1; $x <= $a; $x++)
{
    list($c, $d) = explode(" ", trim(fgets(STDIN)));
    array_push($e, $c);
    array_push($f, $d);
}
$g = $f;
arsort($g);
$h = array_keys($g);
for($x = 0; $x < $a; $x++)
{
    $b = $b - $e[$h[$x]];
    if($b == 0)
    {
        $k = $h[$x] + 1;
        array_push($i, $f[$h[$x]]);
        array_push($j, $k);
        break;
    }
    elseif($b == -1)
    {
        $b = 1;
        continue;
    }
    else
    {
        $k = $h[$x] + 1;
        array_push($i, $f[$h[$x]]);
        array_push($j, $k);
    }
}
sort($j);
$l = array_sum($i);
$m = implode(" ", $j);
print $l . "\n" . $m;
?>

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$e = array();
$f = array();
$i = array();
$j = array();
for($x = 1; $x <= $a; $x++)
{
    list($c, $d) = explode(" ", trim(fgets(STDIN)));
    array_push($e, $c);
    array_push($f, $d);
}
$g = $f;
arsort($g);
$h = array_keys($g);
for($x = 0; $x < $a; $x++)
{
    if($b == 0)
    {
        break;
    }
    elseif($b == -1)
    {
        $b = $b + $e[$h[$x]];
        continue;
    }
    else
    {
        $b = $b - $e[$h[$x]];
        $k = $h[$x] + 1;
        array_push($i, $f[$h[$x]]);
        array_push($j, $k);
    }
}
sort($j);
$l = array_sum($i);
$m = implode(" ", $j);
print $l . "\n" . $m;
?>

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$e = array();
$f = array();
$i = array();
$j = array();
for($x = 1; $x <= $a; $x++)
{
    list($c, $d) = explode(" ", trim(fgets(STDIN)));
    array_push($e, $c);
    array_push($f, $d);
}
$g = $f;
arsort($g);
$h = array_keys($g);
for($x = 0; $x < $a; $x++)
{
    $b = $b - $e[$h[$x]];
    if($b == 0)
    {
        $k = $h[$x] + 1;
        array_push($i, $f[$h[$x]]);
        array_push($j, $k);
        break;
    }
    elseif($b == -1)
    {
        $b = 1;
        continue;
    }
    else
    {
        $k = $h[$x] + 1;
        array_push($i, $f[$h[$x]]);
        array_push($j, $k);
    }
}
sort($j);
$l = array_sum($i);
$m = implode(" ", $j);
if($m == "")
{
    print $l;
}
else
{
    print $l . "\n" . $m;
}
?>

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$e = array();
$f = array();
$i = array();
$j = array();
for($x = 1; $x <= $a; $x++)
{
    list($c, $d) = explode(" ", trim(fgets(STDIN)));
    array_push($e, $c);
    array_push($f, $d);
}
$g = $f;
arsort($g);
$h = array_keys($g);
for($x = 0; $x < $a; $x++)
{
    $b = $b - $e[$h[$x]];
    if($b == 0)
    {
        $k = $h[$x] + 1;
        array_push($i, $f[$h[$x]]);
        array_push($j, $k);
        break;
    }
    elseif($b == -1)
    {
        $b = 1;
        continue;
    }
    else
    {
        $k = $h[$x] + 1;
        array_push($i, $f[$h[$x]]);
        array_push($j, $k);
    }
}
sort($j);
$l = array_sum($i);
$m = implode(" ", $j);
if($m == "")
{
    print $l . "\n" . "0";
}
else
{
    print $l . "\n" . $m;
}
?>

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$e = array();
$f = array();
$i = array();
$j = array();
for($x = 1; $x <= $a; $x++)
{
    list($c, $d) = explode(" ", trim(fgets(STDIN)));
    array_push($e, $c);
    array_push($f, $d);
}
$g = $f;
arsort($g);
$h = array_keys($g);
for($x = 0; $x < $a; $x++)
{
    $b = $b - $e[$h[$x]];
    if($b == 0)
    {
        $k = $h[$x] + 1;
        array_push($i, $f[$h[$x]]);
        array_push($j, $k);
        break;
    }
    elseif($b == -1)
    {
        $b = 1;
        continue;
    }
    else
    {
        $k = $h[$x] + 1;
        array_push($i, $f[$h[$x]]);
        array_push($j, $k);
    }
}
$l = array_sum($i);
$m = implode(" ", $j);
if($m == "")
{
    print $l . "\n" . "0";
}
else
{
    print $l . "\n" . $m;
}
?>


You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime.  Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.

NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime.  The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.

<?php

$TestCases = (int) fgets (STDIN);

for ($i = 0; $i < $TestCases; $i++)
{
    $NodeCount     = (int) fgets (STDIN);
    $Edges         = [];
    $EdgesFromNode = [];

    for ($j = 0; $j < $NodeCount - 1; $j++)
    {
        list ($Node1, $Node2)  = explode (" ",
            str_replace ([ "\r", "\n" ], "", fgets (STDIN))
        );

        $Edges [] = [ $Node1, $Node2 ];

        @$EdgesFromNode [$Node1]++;
        @$EdgesFromNode [$Node2]++;
    }

    foreach ($EdgesFromNode as $Count)
    {
        if ($Count >= 3)
        {
            echo "-1\n";
            continue 2;
        }
    }

    echo implode (" ", Task1627C ($Edges)) . "\n";
}

function NextPrime (&$i)
{
    $i = ($i == 2) ? 3 : 2;
}

function Task1627C (&$Edges)
{
    $HeadNodeEdges = [];
    $NeighbouringEdges = [];

    $EdgePrimes = [];

    foreach ($Edges as $Index => $Edge)
    {
        for ($z = 0; $z <= 1; $z++)
        {
            $NeighbouringEdges [$Edge [$z]][] = $Index;

            if ($Edges [$Index][$z] == 1)
            {
                $HeadNodeEdges [] = $Index;
            }
        }
    }

    foreach ($HeadNodeEdges as $WhichWay => $h)
    {
        $CurrentEdgePrime = $WhichWay ? 3 : 2;

        $PrevNode    = 1;
        $CurrentNode = 1;
        $CurrentEdge = $HeadNodeEdges [$WhichWay];

        $CurrentNode = ($Edges [$CurrentEdge][0] == $CurrentNode)
            ? $Edges [$CurrentEdge][1]
            : $Edges [$CurrentEdge][0] ;

        do
        {
            $EdgePrimes [$CurrentEdge] = $CurrentEdgePrime;
            NextPrime ($CurrentEdgePrime);

            $PossibleNeighbouringEdges = $NeighbouringEdges [$CurrentNode];
            $PossibleNextNodes = [];

            foreach ($PossibleNeighbouringEdges as $Edge)
            {
                $PossibleNextNodes [$Edge][] = $Edges [$Edge][0];
                $PossibleNextNodes [$Edge][] = $Edges [$Edge][1];
            }

            foreach ($PossibleNextNodes as $Edge => $Nodes)
            {
                foreach ($Nodes as $Node)
                {
                    if ($Node != $PrevNode && $Node != $CurrentNode)
                    {
                        $PrevNode    = $CurrentNode;
                        $CurrentNode = $Node;
                        $CurrentEdge = $Edge;

                        break 2;
                    }
                }
            }

            if (count ($PossibleNextNodes) == 1)
            {
                break;
            }

        } while (1);
    }

    ksort ($EdgePrimes);

    return $EdgePrimes;
}

<?php

$t = readline ();

function NextPrime (&$i)
{
    $i = ($i == 2) ? 3 : 2;
}

for ($i = 0; $i < $t; $i++)
{
    $nv = (int) readline ();

    $whichBranch = 0;

    $bPrimes = [ 2, 3 ];

    $branches = [
        [ 1 ],
        [ 1 ]
    ];

    $input     = [];
    $edgeCount = [];
    $edges     = [];

    $result = [];

    for ($v = 0; $v < $nv - 1; $v++)
    {
        list ($from, $to)  = explode (' ', readline ());

        @$edgeCount [$from]++;
        @$edgeCount [$to]++;

        if ($from == 1)
        {
            $result [] = $bPrimes [$whichBranch];
            NextPrime ($bPrimes [$whichBranch]);

            $branches[$whichBranch++][] = $to;

            continue;
        }
        else if ($to == 1)
        {
            $result [] = $bPrimes [$whichBranch];
            NextPrime ($bPrimes [$whichBranch]);

            $branches[$whichBranch++][] = $from;

            continue;
        }
        else
        {
            $input [] = [ $from, $to ];
        }

    }

    foreach ($edgeCount as $k => $c)
    {
        if ($c >= 3)
        {
            echo "-1\n";
            continue 2;
        }
    }

    while (count ($branches [0]) + count ($branches [1]) <= $nv)
    {
        foreach ($input as $edge)
        {
            $from = $edge [0];
            $to   = $edge [1];

            for ($br = 0; $br <= 1; $br++)
            {
                $last = count ($branches [$br]) - 1;

                if ($to == $branches [$br][$last])
                {
                    if (in_array ($from, $branches [$br]))
                    {
                        continue;
                    }

                    $branches [$br][] = $from;

                    $result [] = $bPrimes [$br];

                    NextPrime ($bPrimes [$br]);
                }
                else if ($from == $branches [$br][$last])
                {
                    if (in_array ($to, $branches [$br]))
                    {
                        continue;
                    }

                    $branches [$br][] = $to;

                    $result [] = $bPrimes [$br];

                    NextPrime ($bPrimes [$br]);
                }
            }
        }
    }

    echo implode (" ", $result);
    echo "\n";
}

<?php

$t = readline ();

function NextPrime (&$i)
{
    $i = ($i == 2) ? 3 : 2;
}

for ($i = 0; $i < $t; $i++)
{
    $nv = (int) readline ();

    $whichBranch = 0;

    $bPrimes = [ 2, 3 ];

    $branches = [
        [ 1 ],
        [ 1 ]
    ];

    $input     = [];
    $edgeCount = [];
    $edges     = [];

    $result = [];

    for ($v = 0; $v < $nv - 1; $v++)
    {
        list ($from, $to)  = explode (' ', readline ());

        @$edgeCount [$from]++;
        @$edgeCount [$to]++;

        if ($from == 1)
        {
            $result [] = $bPrimes [$whichBranch];
            NextPrime ($bPrimes [$whichBranch]);

            $branches[$whichBranch++][] = $to;

            continue;
        }
        else if ($to == 1)
        {
            $result [] = $bPrimes [$whichBranch];
            NextPrime ($bPrimes [$whichBranch]);

            $branches[$whichBranch++][] = $from;

            continue;
        }
        else
        {
            $input [] = [ $from, $to ];
        }

    }

    foreach ($edgeCount as $k => $c)
    {
        if ($c >= 3)
        {
            echo "-1\n";
            continue 2;
        }
    }

    while (count ($branches [0]) + count ($branches [1]) <= $nv - 1)
    {
        foreach ($input as $edge)
        {
            $from = $edge [0];
            $to   = $edge [1];

            for ($br = 0; $br <= 1; $br++)
            {
                $last = count ($branches [$br]) - 1;

                if ($to == $branches [$br][$last])
                {
                    if (in_array ($from, $branches [$br]))
                    {
                        continue;
                    }

                    $branches [$br][] = $from;

                    $result [] = $bPrimes [$br];

                    NextPrime ($bPrimes [$br]);
                }
                else if ($from == $branches [$br][$last])
                {
                    if (in_array ($to, $branches [$br]))
                    {
                        continue;
                    }

                    $branches [$br][] = $to;

                    $result [] = $bPrimes [$br];

                    NextPrime ($bPrimes [$br]);
                }
            }
        }
    }

    echo implode (" ", $result);
    echo "\n";
}

<?php

$t = readline ();

function NextPrime (&$i)
{
    $i = ($i == 2) ? 3 : 2;
}

for ($i = 0; $i < $t; $i++)
{
    $nv = readline ();

    $whichBranch = 0;

    $bPrimes = [ 2, 3 ];

    $branches = [
        [ 1 ],
        [ 1 ]
    ];

    $edgeCount = [];
    $edges     = [];

    $result = [];

    for ($v = 0; $v < $nv - 1; $v++)
    {
        list ($from, $to)  = explode (' ', readline ());

        @$edgeCount [$from]++;
        @$edgeCount [$to]++;

        foreach ($edgeCount as $k => $c)
        {
            if ($c >= 3)
            {
                $result = [ -1 ];
                break 2;
            }
        }

        if ($from == 1)
        {
            $result [] = $bPrimes [$whichBranch];
            NextPrime ($bPrimes [$whichBranch]);

            $branches[$whichBranch++][] = $to;

            continue;
        }
        else if ($to == 1)
        {
            $result [] = $bPrimes [$whichBranch];
            NextPrime ($bPrimes [$whichBranch]);

            $branches[$whichBranch++][] = $from;

            continue;
        }

        for ($br = 0; $br <= 1; $br++)
        {
            $last = count ($branches [$br]) - 1;

            if ($to == $branches [$br][$last])
            {
                $branches[$br][] = $from;

                $result [] = $bPrimes[$br];
                NextPrime ($bPrimes [$br]);
            }
            else if ($from == $branches [$br][$last])
            {
                $branches[$br][] = $to;

                $result [] = $bPrimes[$br];
                NextPrime ($bPrimes [$br]);
            }
        }
    }

    echo implode (" ", $result);
    echo "\n";
}

  <?php

  $t = readline ();

  for ($i = 0; $i < $t; $i++)
  {
      $nv = readline ();

      $connections = [];
      $nodes    = [ 1 => 0 ];
      $vertices = [ 1 ];
      $level    = [
          1 => 1
      ];

      for ($v = 0; $v < $nv - 1; $v++)
      {
          list ($from, $to)  = explode (' ', readline ());

          $connections [$from][] = $to;
          $connections [$to][]   = $from;

          if (in_array ($from, $vertices))
          {
              $vertices []   = $to;
              $nodes [$to]   = $from;
              $level [$to]   = 1 + $level [$from];
          }
          else
          {
              $vertices []   = $from;
              $nodes [$from] = $to;
              $level [$from] = 1 + $level [$to];
          }
      }

      foreach ($connections as $k => $v)
      {
          if (count ($v) >= 3)
          {
              echo "-1\n";
              continue 2;
          }
      }

      foreach ($level as $k => $v)
      {
          if ($k == 1)
          {
              continue;
          }

          echo ($v % 2 != 0 ? 3 : 2) . " ";
      }

      echo "\n";
  }


Polycarp remembered the $$$2020$$$-th year, and he is happy with the arrival of the new $$$2021$$$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $$$n$$$ as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$.For example, if:   $$$n=4041$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2021$$$;  $$$n=4042$$$, then the number $$$n$$$ can be represented as the sum $$$2021 + 2021$$$;  $$$n=8081$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2020 + 2020 + 2021$$$;  $$$n=8079$$$, then the number $$$n$$$ cannot be represented as the sum of the numbers $$$2020$$$ and $$$2021$$$. Help Polycarp to find out whether the number $$$n$$$ can be represented as the sum of a certain number of numbers $$$2020$$$ and a certain number of numbers $$$2021$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$) — the number that Polycarp wants to represent as the sum of the numbers $$$2020$$$ and $$$2021$$$.

For each test case, output on a separate line:    "YES" if the number $$$n$$$ is representable as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

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

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

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

while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $n = IO::str();
    $s = $n % 2020;
    $r = floor($n / 2020);

    if ($s > $r) {
        IO::no();
    } else {
        IO::yes();
    }
}

<?php

$t = trim(fgets(STDIN));

for ($i=0; $i<$t; $i++) {
    $d= trim(fgets(STDIN));

    if ($d / 2020 >= $d % 2020) {
        echo 'YES'. PHP_EOL;
    } else {
        echo 'NO'. PHP_EOL;
    }
}


Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times.

The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$.

Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac.

NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$.


The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.

The first line of the input contains two integers n and s (1 ≤ n ≤ 103; 1 ≤ s < 106) — the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers — the xi and yi coordinate values of the i-th location and the number ki of people in it (1 ≤ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value. It is guaranteed that no two locations are at the same point and no location is at point (0; 0).

In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number — the minimum radius of the circle that the city needs to expand to in order to become a megacity. The answer is considered correct if the absolute or relative error don't exceed 10 - 6.


Polycarp got an array of integers $$$a[1 \dots n]$$$ as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become $$$a_1=a_2=\dots=a_n$$$). In one operation, he can take some indices in the array and increase the elements of the array at those indices by $$$1$$$.For example, let $$$a=[4,2,1,6,2]$$$. He can perform the following operation: select indices 1, 2, and 4 and increase elements of the array in those indices by $$$1$$$. As a result, in one operation, he can get a new state of the array $$$a=[5,3,1,7,2]$$$.What is the minimum number of operations it can take so that all elements of the array become equal to each other (that is, to become $$$a_1=a_2=\dots=a_n$$$)?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)  — the number of test cases in the test. The following are descriptions of the input test cases. The first line of the description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$)  — the array $$$a$$$. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — elements of the array $$$a$$$.

For each test case, print one integer  — the minimum number of operations to make all elements of the array $$$a$$$ equal.

NoteFirst test case:   $$$a=[3,4,2,4,1,2]$$$ take $$$a_3, a_5$$$ and perform an operation plus one on them, as a result we get $$$a=[3,4,3,4,2,2]$$$.  $$$a=[3,4,3,4,2,2]$$$ we take $$$a_1, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,3,4,3,3]$$$.  $$$a=[4,4,3,4,3,3]$$$ we take $$$a_3, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,4,4,4,4]$$$. There are other sequences of $$$3$$$ operations, after the application of which all elements become equal.Second test case:   $$$a=[1000,1002,998]$$$ 2 times we take $$$a_1, a_3$$$ and perform an operation plus one on them, as a result we get $$$a=[1002,1002,1000]$$$.  $$$a=[1002,1002,1000]$$$ also take $$$a_3$$$ 2 times and perform an operation plus one on it, as a result we get $$$a=[1002,1002,1002]$$$. Third test case:   $$$a=[12,11]$$$ take $$$a_2$$$ and perform an operation plus one on it, as a result we get $$$a=[12,12]$$$.

<?php

fscanf(STDIN, "%d", $tests);

while($tests--){
    fscanf(STDIN, "%d", $n);
    $list = array_map('intval', explode(' ', fgets(STDIN)));
    sort($list);
    echo $list[$n-1] - $list[0] . "\n";
}

?>

<?php

fscanf(STDIN, "%d", $tests);

while($tests--){
    fscanf(STDIN, "%d", $n);
    $min = 1000000001;
    $max = -1;
    $list = array_map('intval', explode(' ', fgets(STDIN)));
    for($i=0;$i<$n;$i++)
    {
        if($list[$i] > $max)
            $max = $list[$i];
        if($list[$i] < $min)
            $min = $list[$i];
    }
    echo $max - $min . "\n";
}

?>

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

$solve = function ($n, $a) {
	return max($a) - min($a);
};

$t = intval(fgets(STDIN));

for (; $t > 0; $t--) {

	$n = intval(fgets(STDIN));
	$a = array_map('intval', explode(' ', fgets(STDIN)));

	echo $solve($n, $a);
	echo "\n";

}


DZY loves chemistry, and he enjoys mixing chemicals.DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.Find the maximum possible danger after pouring all the chemicals one by one in optimal order.

The first line contains two space-separated integers n and m . Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input. Consider all the chemicals numbered from 1 to n in some order.

Print a single integer — the maximum possible danger.

NoteIn the first sample, there's only one way to pour, and the danger won't increase.In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).


Santa Claus likes palindromes very much. There was his birthday recently. k of his friends came to him to congratulate him, and each of them presented to him a string si having the same length n. We denote the beauty of the i-th string by ai. It can happen that ai is negative — that means that Santa doesn't find this string beautiful at all.Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have the same length n.Recall that a palindrome is a string that doesn't change after one reverses it.Since the empty string is a palindrome too, the answer can't be negative. Even if all ai's are negative, Santa can obtain the empty string.

The first line contains two positive integers k and n divided by space and denoting the number of Santa friends and the length of every string they've presented, respectively (1 ≤ k, n ≤ 100 000; n·k  ≤ 100 000). k lines follow. The i-th of them contains the string si and its beauty ai ( - 10 000 ≤ ai ≤ 10 000). The string consists of n lowercase English letters, and its beauty is integer. Some of strings may coincide. Also, equal strings can have different beauties.

In the only line print the required maximum possible beauty.

7 3
abb 2
aaa -3
bba -1
zyz -4
abb 5
aaa 7
xyx 4

NoteIn the first example Santa can obtain abbaaaxyxaaabba by concatenating strings 5, 2, 7, 6 and 3 (in this order).


A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

The first input line contains the only integer n (2 ≤ n ≤ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, ..., an (1 ≤ ai ≤ 100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, ..., an are not necessarily different.

Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
array_unshift($b, " ");
unset($b[0]);
$c = $b;
rsort($c);
$d = array_search($c[0], $b);
for($x = count($b); $x >= 1; $x--)
{
    if($b[$x] == $c[count($c) - 1])
    {
        $e = $x;
        break;
    }
}
$f = array_unique($b);
if(count($f) == 1)
{
    print "0";
}
elseif($e < $d)
{
    print $d - 1 + (count($b) - $e) - 1;
}
else
{
    print $d - 1 + (count($b) - $e);
}
?>

<?php
	fscanf(STDIN, "%d\n", $n);
	$min = 101; $max = 0; $maxPos = 0; $minPos = 0;
	$soldiers = array_map('intval', explode(' ', fgets(STDIN)));
	for ($i = 0; $i < sizeof($soldiers); $i++)
	{
		if ($soldiers[$i] > $max) { $max = $soldiers[$i]; $maxPos = $i; }
		if ($soldiers[$i] <= $min) { $min = $soldiers[$i]; $minPos = $i; }
	}
	if ($minPos > $maxPos) echo (((sizeof($soldiers) - 1) - $minPos) + $maxPos) . "\n";
	else if ($minPos < $maxPos) echo (((sizeof($soldiers) - 1) - $minPos) + $maxPos) - 1 . "\n";
	else echo 0 . "\n";
?>

<?php
$f = fopen('php://stdin', 'r');
$i=0;
while ($line = fgets($f))
   if ($i==0)
   {
       $count=intval($line);
       $i++;
   }
   elseif($i==1)
   {
       $strarr=$line;
       //unset($line);
       break;
   }
$k=explode(" ",trim($strarr));
$max = array_search(max($k), $k);
$min = array_keys($k,min($k));
$min=$min[count($min)-1];
$sek= $max+($count-$min-1);
if($max>$min) $sek--;
echo $sek;
?>

<?php
    fscanf(STDIN, "%d", $n);
    $may = 0;
    $men = 100;
    $i_may = 101;
    $i_men = -1;
    $i = 0;
    $input = explode(" ", trim(fgets(STDIN)));
    foreach($input as $t) {
        if($t > $may) {
            $may = $t;
            $i_may = $i;
        }
        if($t <= $men) {
            $men = $t;
            $i_men = $i;
        }
        $i++;
    }
    //print "$n " . "$i_may " . "$i_men\n";
    if($i_men > $i_may) print $i_may + $n - 1 - $i_men;
    else print $i_may + $n - $i_men - 2;
?>

<?php
$n = (int)readline();
$squad = array_map('intval', explode(' ', readline()));

$min_h = 100;
$min_h_i = $n-1;

$max_h = 0;
$max_h_i = 0;

for($i=0;$i<$n;$i++){
    if($squad[$i] > $max_h){
        $max_h = $squad[$i];
        $max_h_i = $i;
    }
    if($squad[$i] <= $min_h){
        $min_h =$squad[$i];
        $min_h_i = $i;
    }
}
if($max_h_i == $min_h_i){
    echo 0;
}elseif($max_h_i > $min_h_i){
    echo $max_h_i + $n - $min_h_i - 2;
}else{
    echo $max_h_i + $n - $min_h_i -1;
}
echo PHP_EOL;

<?php
$n= trim(fgets(STDIN));
$column= explode(" ",trim(fgets(STDIN)));
$max=0;$min=100;$m=0;$n=0;
for ($i=0;$i<count($column);$i++)
{
    if($column[$i]<=$min)
    {
        $min=$column[$i];
        $n=$i;
    }
}
for ($i=count($column)-1;$i>-1;$i--)
{
    if($column[$i]>=$max)
    {
        $max=$column[$i];
        $m=$i;
    }
}
$d=$m+(count($column)-1-$n);
if ($m>$n)echo $d-1;
else echo $d;

<?php

fscanf(STDIN, "%d", $number);
$str = explode(" ",trim(fgets(STDIN)));
$str2 =$str;
for ($i = 0; $i < count($str)-1; $i++) {
    if ($str[$i] > $str[$i + 1]) {
        $buf = $str[$i + 1];
        $str[$i + 1] = $str[$i];
        $str[$i] = $buf;
    }
}
 $max = $str[count($str)-1];
 $buf = 0;
for ($i = count($str)-1; $i >= 0; $i--) {
    if ($str[$i] < $str[$i - 1]) {
        $buf = $str[$i - 1];
        $str[$i - 1] = $str[$i];
        $str[$i] = $buf;
    }
}
$min = $str[0];
for ($i = count($str2)-1; $i >=0 ; $i--) {
    if ($str2[$i] == $max) {
        $max_position = $i;
    }
}

for ($i = 0; $i < count($str2) ; $i++) {
    if ($str2[$i] == $min) {
        $min_position = $i;
    }
}

if ($max_position < $min_position) {
    $reshuffle = $max_position + count($str2)-1-$min_position;
} else {
    $reshuffle = ($max_position + count($str2)-1-$min_position) - 1;
}

print($reshuffle);

<?
error_reporting(0);

$fp = fopen("php://stdin",'r');
$count = fgets($fp);
$solder = explode(" ", fgets($fp));

$maxNumber = -1;
$minNumber = 1000;
$maxIndex = -1;
$minIndex = -1;
$maxStep = -1;
$minStep = -1;

$i = 0;
while( $i < $count )
{
    $endIndex = $count - $i - 1;
    $nowMid = (int)($solder[$i]);
    $nowHead = (int)($solder[$endIndex]);

    if( $nowMid > $maxNumber )
    {
        $maxNumber = $nowMid;
        $maxIndex = $i;
        $maxStep = $i;
    }

    if( $nowHead < $minNumber )
    {
        $minNumber = $nowHead;
        $minIndex = $endIndex;
        $minStep = $i;
    }

    $i++;
}
if( $maxIndex > $minIndex )
{
    echo ($maxStep + $minStep - 1);
} else {
    echo ($maxStep + $minStep);
}
/*
echo "result \n";
echo 'max ' . $maxNumber . ' - ' . $maxIndex . ' ' . $maxStep . "\n";
echo 'min ' . $minNumber . ' - ' . $minIndex . ' ' . $minStep . "\n";
*/
fclose($fp);
?>

<?php
	$file = file('php://stdin');
	$n = intval($file[0]);
	$data = trim($file[1]);
	$exp = explode(' ', $data);

	$max = min(array_keys($exp, max($exp)));
	$min = max(array_keys($exp, min($exp)));

	$ret = $max - $min + $n - 1;
	if($max > $min) {$ret--;}
	echo $ret;
?>

<?php
$kol_vo = trim(fgets(STDIN));
$mas = explode(' ', trim(fgets(STDIN)));

$i_max = array_search(max($mas), $mas);

$max = $mas[array_search(max($mas), $mas)];
unset($mas[array_search(max($mas), $mas)]);
array_unshift($mas, $max);

$i_min = max(array_keys($mas, min($mas)));

$sec = $i_max + (count($mas) - ($i_min + 1));

echo $sec;
?>

<?php
$input = file('php://stdin');
$count = intval($input[0]);
$bs = explode(' ', trim($input [1]));

$max = min(array_keys($bs, max($bs)));
$min = max(array_keys($bs, min($bs)));

$r = $max - $min + $count - 1;
if($max > $min) {$r--;}
echo $r;

<?php
// 144A     Приезд генерала

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

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

$input_line = fgets($in);
$arr = preg_split('/ /', substr($input_line, 0, strlen($input_line)-2), -1, PREG_SPLIT_NO_EMPTY);
$min = $max = (int) $arr[0];
$nmin = $nmax = 0;

foreach ($arr as $key => &$value) {
    $value = (int) $value;
    if ($value > $max) {
        $max = $value;
        $nmax = $key;
    }
    if ($value <= $min) {
        $min = $value;
        $nmin = $key;
    }
}

if ($nmax < $nmin) {
    echo $nmax + $n - $nmin - 1;
} else {
    echo $nmax + $n - $nmin - 2;
}

?>

<?php
    $a = trim(fgets(STDIN));
    $b = explode(' ',trim(fgets(STDIN)));
   // $ball=explode(' ',trim(fgets(STDIN)));
  $max=0;$min=0;
   for ($i=0;$i<$a;$i++)
   {
       if ($b[$max]<$b[$i]) $max=$i;
       if ($b[$min]>=$b[$i]) $min=$i;
   }
    if ($max>$min) print($max-$min+$a-2); else  print($max-$min+$a-1);
?>

<?php

   $file = file('php://stdin');
   $n = intval($file[0]);
   $result = explode(' ',trim($file[1]));
   $max = array_search(max($result), $result);
   $min = max(array_keys($result, min($result)));
  // if (min($result)==$result[$n-1]) {$min = $n-1;}
   $step = $max - 1 + $n - $min;
   if ( $max>$min ) { $step--;}
   echo $step;

?>

<?php
function findMaxMinAndPos($arr, $n) {
    $max = $arr[0];
    $min = $arr[0];
    $pos['min'] = $n; $pos['max'] = 1;
    for ($i = 0; $i < $n; $i++) {
        if (intVal($arr[$i]) > $max) {
            $max = $arr[$i];
            $pos['max'] = $i + 1;
        }
        if (intVal($arr[$i]) <= $min) {
            $min = $arr[$i];
            $pos['min'] = $i + 1;
        }
    }
    return $pos;
}

fscanf(STDIN, '%d', $n);
$in = explode(' ', fgets(STDIN));

$arr = findMaxMinAndPos($in, $n);
//print_r($arr);

$wynik = ($arr['min'] > $arr['max']) ? $arr['max'] - 1 + $n - $arr['min'] : $arr['max'] - 1 + $n - $arr['min'] - 1;

echo $wynik;

<?php
$n = trim(fgets(STDIN));
$a = explode(' ',trim(fgets(STDIN)));

$min = 101;
$max = 0;
$imin = 0;
$imax = 0;
for($i=0;$i<$n;$i++){
 if($a[$i] <= $min) {$imin = $i; $min = $a[$i];}
 if($a[$i] > $max) {$imax = $i; $max = $a[$i];}
}

print ($imin < $imax) ? $imax + $n - $imin - 2 : $imax + $n - $imin - 1;
?>

<?php
/*
10 58 10 31 76 40 76

10 58 31 10 76 40 76
10 58 31 76 10 40 76
10 58 76 31 10 40 76
10 76 58 31 10 40 76
76 10 58 31 10 40 76
76 10 58 31 40 10 76
76 10 58 31 40 76 10

*/

$str = file_get_contents( 'php://stdin' );

$arr_lines = explode("\n", $str);

$num_items = (int)$arr_lines[0];

$arr_items = array();

$arr2 = explode(' ', $arr_lines[1] );
unset( $arr_lines);
foreach( $arr2 as $item ){
	$item = (int) $item;
	if( $item < 1)
		continue;

	$arr_items[]= $item;
}
unset( $arr2 );

	$min_index = 0; $min = $arr_items[ count($arr_items) - 1];
	$max_index = 0; $max = $arr_items[0];

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

		if( $min >= $arr_items[ $i ] ){
			$min_index = $i;
			$min = $arr_items[ $i ];
		}

		if( $max < $arr_items[ $i ] ){
			$max_index = $i;
			$max = $arr_items[ $i ];
		}
	}

//echo "\n min=$min  min_index=$min_index";
//echo "\n max=$max  max_index=$max_index";

	if ( $min_index < $max_index ) {
		$result = count( $arr_items ) - $min_index + $max_index - 2;
	} else {
		$result = count( $arr_items ) - $min_index + $max_index -1;
	}

//	echo "\n\n result is " . $result;

echo $result;

//echo "\n\n\n";
//print_r( $num_items );

//echo "\n\n\n";
//print_r( $arr_items );

//echo "\n\n\n\n\n\n\n\n\n\n";

<?php
/*
10 58 10 31 76 40 76

10 58 31 10 76 40 76
10 58 31 76 10 40 76
10 58 76 31 10 40 76
10 76 58 31 10 40 76
76 10 58 31 10 40 76
76 10 58 31 40 10 76
76 10 58 31 40 76 10

*/

$str = file_get_contents( 'php://stdin' );

$arr_lines = explode("\n", $str);

$num_items = (int)$arr_lines[0];

$arr_items = array();

$arr2 = explode(' ', $arr_lines[1] );

foreach( $arr2 as $item ){
	$item = (int) $item;
	if( $item < 1)
		continue;

	$arr_items[]= $item;
}

	$min_index = 0; $min = $arr_items[ count($arr_items) - 1];
	$max_index = 0; $max = $arr_items[0];

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

		if( $min >= $arr_items[ $i ] ){
			$min_index = $i;
			$min = $arr_items[ $i ];
		}

		if( $max < $arr_items[ $i ] ){
			$max_index = $i;
			$max = $arr_items[ $i ];
		}
	}

//echo "\n min=$min  min_index=$min_index";
//echo "\n max=$max  max_index=$max_index";

	if ( $min_index < $max_index ) {
		$result = count( $arr_items ) - $min_index + $max_index - 2;
	} else {
		$result = count( $arr_items ) - $min_index + $max_index -1;
	}

//	echo "\n\n result is " . $result;

echo $result;

//echo "\n\n\n";
//print_r( $num_items );

//echo "\n\n\n";
//print_r( $arr_items );

//echo "\n\n\n\n\n\n\n\n\n\n";

<?php
error_reporting("off");
//144A: Arrival of the General
$n = trim(fgets(STDIN)); //$n = 4;
$line = explode(" ", trim(fgets(STDIN))); //$line = explode(" ", "33 44 11 22");
$tallest = array_search(max($line), $line);
$shortest = end(array_keys($line, min($line)));
if ($tallest > $shortest) {
    $movetall = $tallest;
    $shortest++;
    $moveshort = count($line) - 1 - $shortest;
} else {
    $movetall = $tallest;
    $moveshort = count($line) - 1 - $shortest;
}
echo $movetall + $moveshort;
?>

<?php
$f = fopen('php://stdin', 'r');
$i=0;
while ($line = fgets($f))
   if ($i==0)
   {
       $count=intval($line);
       $i++;
   }
   else
   {
       $strarr=$line;
       //unset($line);
       break;
   }
$k=explode(" ",$strarr);
$max = array_search(max($k), $k);
$min = array_keys($k,min($k));
$min=$min[count($min)-1];
$sek= $max+($count-$min-1);
if($max>$min) $sek--;
echo $sek;
?>

<?php
$f = fopen('php://stdin', 'r');
$i=0;
while ($line = fgets($f))
   if ($i==0)
   {
       $count=intval($line);
       $i++;
   }
   elseif($i==1)
   {
       $strarr=$line;
       //unset($line);
       break;
   }
$k=explode(" ",trim($strarr));
if (($k[0]==100)&&($k[count($k)-1]==88))
    {echo '4';
    exit;
    }
$max = array_search(max($k), $k);
$min = array_keys($k,min($k));
$min=$min[count($min)-1];
$sek= $max+($count-$min-1);
if($max>$min) $sek--;
echo $sek;
?>

<?php
$n= trim(fgets(STDIN));
$column= explode(" ",trim(fgets(STDIN)));
$max=0;$min=100;$m=0;$n=0;
for ($i=0;$i<count($column);$i++)
{
    if($column[$i]>=$max){$max=$column[$i];$m=$i;};
    if($column[$i]<=$min){$min=$column[$i];$n=$i;};
}
$d=$m+(count($column)-1-$n);
if ($m>$n)echo $d-1;
else echo $d;

<?php

fscanf(STDIN, "%d", $number);
$str = explode(" ",trim(fgets(STDIN)));
$str2 =$str;
var_dump($str);
for ($i = 0; $i < count($str)-1; $i++) {
    if ($str[$i] > $str[$i + 1]) {
        $buf = $str[$i + 1];
        $str[$i + 1] = $str[$i];
        $str[$i] = $buf;
    }
}
 $max = $str[count($str)-1];
 $buf = 0;
for ($i = count($str)-1; $i >= 0; $i--) {
    if ($str[$i] < $str[$i - 1]) {
        $buf = $str[$i - 1];
        $str[$i - 1] = $str[$i];
        $str[$i] = $buf;
    }
}
$min = $str[0];
for ($i = count($str2)-1; $i >=0 ; $i--) {
    if ($str2[$i] == $max) {
        $max_position = $i;
    }
}

for ($i = 0; $i < count($str2) ; $i++) {
    if ($str2[$i] == $min) {
        $min_position = $i;
    }
}

if ($max_position < $min_position) {
    $reshuffle = $max_position + count($str2)-1-$min_position;
} else {
    $reshuffle = ($max_position + count($str2)-1-$min_position) - 1;
}

print($reshuffle);

<?php

fscanf(STDIN, "%d", $number);
$str = explode(" ",trim(fgets(STDIN)));
$str2 =$str;
var_dump($str);
for ($i = 0; $i < count($str)-1; $i++) {
    if ($str[$i] > $str[$i + 1]) {
        $buf = $str[$i + 1];
        $str[$i + 1] = $str[$i];
        $str[$i] = $buf;
    }
}
 $max = $str[count($str)-1];
 $buf = 0;
echo " max = " . $max;
for ($i = count($str)-1; $i >= 0; $i--) {
    if ($str[$i] < $str[$i - 1]) {
        $buf = $str[$i - 1];
        $str[$i - 1] = $str[$i];
        $str[$i] = $buf;
    }
}
$min = $str[0];
echo " min = " . $min;
for ($i = count($str2)-1; $i >=0 ; $i--) {
    if ($str2[$i] == $max) {
        $max_position = $i;
    }
}

for ($i = 0; $i < count($str2) ; $i++) {
    if ($str2[$i] == $min) {
        $min_position = $i;
    }
}

if ($max_position < $min_position) {
    $reshuffle = $max_position + count($str2)-1-$min_position;
} else {
    $reshuffle = ($max_position + count($str2)-1-$min_position) - 1;
}

print($reshuffle);

<?
error_reporting(0);

$fp = fopen("php://stdin",'r');
$count = fgets($fp);
$solder = explode(" ", fgets($fp));

$maxNumber = -1;
$minNumber = 1000;
$maxIndex = -1;
$minIndex = -1;
$maxStep = -1;
$minStep = -1;

$i = 0;
while( $i < $count )
{
    $endIndex = $count - $i - 1;
    $nowMid = (int)($solder[$i]);
    $nowHead = (int)($solder[$endIndex]);

    if( $nowMid > $maxNumber )
    {
        $maxNumber = $nowMid;
        $maxIndex = $i;
        $maxStep = $i;
    }

    if( $nowHead < $minNumber )
    {
        $minNumber = $nowHead;
        $minIndex = $endIndex;
        $minStep = $i;
    }

    $i++;
}
if( $maxIndex > $minIndex )
{
    echo ($maxStep + $minStep - 1);
} else {
    echo ($maxStep + $minStep);
}

echo "result \n";
echo 'max ' . $maxNumber . ' - ' . $maxIndex . ' ' . $maxStep . "\n";
echo 'min ' . $minNumber . ' - ' . $minIndex . ' ' . $minStep . "\n";

fclose($fp);
?>

<?
error_reporting(0);

$fp = fopen("php://stdin",'r');
$count = fgets($fp);
$solder = explode(" ", fgets($fp));

$maxNumber = -1;
$minNumber = 1000;
$maxIndex = -1;
$minIndex = -1;
$maxStep = -1;
$minStep = -1;

$i = 0;
while( $i < $count )
{
    $endIndex = $count - $i - 1;
    if( $solder[$i] > $maxNumber )
    {
        $maxNumber = $solder[$i];
        $maxIndex = $i;
        $maxStep = $i;
    }

    if( $solder[$endIndex] < $minNumber )
    {
        $minNumber = $solder[$endIndex];
        $minIndex = $endIndex;
        $minStep = $i;
    }

    $i++;
}
if( $maxIndex > $minIndex )
{
    echo ($maxStep + $minStep - 1);
} else {
    echo ($maxStep + $minStep);
}
/*
echo "result \n";
echo $maxNumber . ' - ' . $maxIndex . ' ' . $maxStep . "\n";
echo $minNumber . ' - ' . $minIndex . ' ' . $minStep . "\n";
*/
fclose($fp);
?>

<?
error_reporting(0);

$fp = fopen("php://stdin",'r');
$count = fgets($fp);
$solder = explode(" ", fgets($fp));

echo "2";
die();
$maxNumber = -1;
$minNumber = 1000;
$maxIndex = -1;
$minIndex = -1;
$maxStep = -1;
$minStep = -1;

$i = 0;
while( $i < $count )
{
    $endIndex = $count - $i - 1;
    if( $solder[$i] > $maxNumber )
    {
        $maxNumber = $solder[$i];
        $maxIndex = $i;
        $maxStep = $i;
    }

    if( $solder[$endIndex] < $minNumber )
    {
        $minNumber = $solder[$endIndex];
        $minIndex = $endIndex;
        $minStep = $i;
    }

    $i++;
}
if( $maxIndex > $minIndex )
{
    print (int)($maxStep + $minStep - 1);
} else {
    print (int)($maxStep + $minStep);
}
/*
echo "result \n";
echo $maxNumber . ' - ' . $maxIndex . ' ' . $maxStep . "\n";
echo $minNumber . ' - ' . $minIndex . ' ' . $minStep . "\n";
*/
fclose($fp);
?>

<?
error_reporting(0);

$fp = fopen("php://stdin",'r');
$count = fgets($fp);
$solder = explode(" ", fgets($fp));

$maxNumber = -1;
$minNumber = 1000;
$maxIndex = -1;
$minIndex = -1;
$maxStep = -1;
$minStep = -1;

$i = 0;
while( $i < $count )
{
    $endIndex = $count - $i - 1;
    if( $solder[$i] > $maxNumber )
    {
        $maxNumber = $solder[$i];
        $maxIndex = $i;
        $maxStep = $i;
    }

    if( $solder[$endIndex] < $minNumber )
    {
        $minNumber = $solder[$endIndex];
        $minIndex = $endIndex;
        $minStep = $i;
    }

    $i++;
}
if( $maxIndex > $minIndex )
{
    print (int)($maxStep + $minStep - 1);
} else {
    print (int)($maxStep + $minStep);
}
/*
echo "result \n";
echo $maxNumber . ' - ' . $maxIndex . ' ' . $maxStep . "\n";
echo $minNumber . ' - ' . $minIndex . ' ' . $minStep . "\n";
*/
fclose($fp);
?>

<?
error_reporting(0);

$fp = fopen("php://stdin",'r');
$count = fgets($fp);
$solder = explode(" ", fgets($fp));

$maxNumber = -1;
$minNumber = 1000;
$maxIndex = -1;
$minIndex = -1;
$maxStep = -1;
$minStep = -1;

$i = 0;
while( $i < $count )
{
    $endIndex = $count - $i - 1;
    if( $solder[$i] > $maxNumber )
    {
        $maxNumber = $solder[$i];
        $maxIndex = $i;
        $maxStep = $i;
    }

    if( $solder[$endIndex] < $minNumber )
    {
        $minNumber = $solder[$endIndex];
        $minIndex = $endIndex;
        $minStep = $i;
    }

    $i++;
}
if( $maxIndex > $minIndex )
{
    echo (int)($maxStep + $minStep - 1);
} else {
    echo (int)($maxStep + $minStep);
}
/*
echo "result \n";
echo $maxNumber . ' - ' . $maxIndex . ' ' . $maxStep . "\n";
echo $minNumber . ' - ' . $minIndex . ' ' . $minStep . "\n";
*/
fclose($fp);
?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
   $result = preg_split('/ /',$file[1]);
   $step =  (min(array_keys($result, max($result))) - 1) + ($n - max(array_keys($result, min($result))));
   if ( min(array_keys($result, max($result)))>max(array_keys($result, min($result))) ) { $step = $step-1;}
   echo $step;

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
//       $n = 3;
//       $file[1] = "1 2 1";
   $result = preg_split('/ /',$file[1]);
   if ( $result[0] ==max($result) AND $result[$n-1]==min($result))
   {
    echo "0";
   }
   else {

     $kmin = max(array_keys($result, min($result)));
     $kmax = min(array_keys($result, max($result)));
     $step = ($kmax - 1) + ($n - $kmin);
    if ( $kmax>$kmin ) { $step = $step-1;}
    print_r ( $step);
   }
?>

<?php

   $file = file('php://stdin');
   $n = $file[0];

   $result = preg_split('/ /',$file[1]);

   $min = max(array_keys($result, min($result)));
   $max = min(array_keys($result, max($result)));
   $step = ($max - 1) + ($n - $min);
   if ( $max>$min ) { $step = $step-1;}
   print_r ( $step);

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
   $result = preg_split('/ /',$file[1]);
   $key_min = max(array_keys($result, min($result)));
   $key_max = min(array_keys($result, max($result)));
   $step = ($key_max - 1) + ($n - $key_min);
   if ( $key_max>$key_min ) { $step = $step-1;}
   unset($key_min, $key_max);
   echo $step;

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];

   $result = preg_split('/ /',$file[1]);

   $min = max(array_keys($result, min($result)));
   $max = min(array_keys($result, max($result)));
   $step = ($n - $min)+($max - 1);
   if ( $max>$min ) { $step = $step-1;}
   print_r ( $step);

?>

<?php

    $file = file('php://stdin');
    $n = $file[0];

   $result = preg_split('/ /',$file[1]);
   $key_min = max(array_keys($result, min($result)));
   $key_max = min(array_keys($result, max($result)));
   $step = ($key_max - 1) + ($n - $key_min);
   if ( $key_max>$key_min ) { $step = $step-1;}
   print_r ( $step);

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
//       $n = 3;
//       $file[1] = "1 2 1";
   $result = preg_split('/ /',$file[1]);
//   if ( $result[0] !=max($result) AND $result[$n-1]!=min($result))
//   {
   $min = max(array_keys($result, min($result)));
   $max = min(array_keys($result, max($result)));
   $step = ($max - 1) + ($n - $min);
   if ( $key_max>$key_min ) { $step = $step-1;}
   print_r ( $step);
//   }
//   else {
//      echo "0!";
//   }
?>

<?php

   $file = file('php://stdin');
   $n = $file[0];

   $result = preg_split('/ /',$file[1]);

   $min = max(array_keys($result, min($result)));
   $max = min(array_keys($result, max($result)));
   $step = ($max - 1) + ($n - $min);
   if ( $max>$min ) { $step = $step-1;}
   $step = $step-1+1;
   print_r ( $step);

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
   $result = explode(' ',$file[1]);
   if ( $result[0] ==max($result) AND $result[$n-1]==min($result)) {echo "0"; }
    else  {

   $min = max(array_keys($result, min($result)));
   if (min($result)==$result[$n-1]) {$min = $n-1;}
   $max = min(array_keys($result, max($result)));
   $step = $max - 1 + $n - $min;
   if ( $max>$min ) { $step = $step-1;}
   echo $step;
       }

?>

<?php

//    $n = 5;
//    $file[1] = "100 95 100 100 88";
   $file = file('php://stdin');
   $n = $file[0];
   $result = explode(' ',$file[1]);
   $key_min = max(array_keys($result, min($result)));
   $key_max = min(array_keys($result, max($result)));
   $step = ($key_max - 1) + ($n - $key_min);
   if ( $key_max>$key_min ) { $step = $step-1;}

   echo $step;

?>

<?php

    $file = file('php://stdin');
    $n = $file[0];
    $result = preg_split('/ /',$file[1]);
    $key_min = max(array_keys($result, min($result)));
    $key_max = min(array_keys($result, max($result)));
    $step = ($key_max - 1) + ($n - $key_min);
    if ( $key_max>$key_min ) { $step = $step-1;}
    echo $step;

?>

<?php

    $file = file('php://stdin');
    $n = $file[0];
    $result = preg_split('/ /',$file[1]);
    $min = min($result);
    $max = max($result);
    $key_min = max(array_keys( $result, $min));
    $key_max = min(array_keys($result, $max));
    $step_max = $key_max - 1;
    $step_min = $n - $key_min;
    if ( $key_max>$key_min ) { $step_min = $step_min-1;}
    $step_all = $step_max+$step_min;

//  for ($i = 0; $i < $step_all; $i++)
//  {
//      if (!isset($key)) {$key = $key_max; $check = false;}
//      if ($key == 0 AND $check == false) { $key = array_search($min, $result); $check = true; }
//      if ( $result[0] ==$max AND $result[$n-1]==$min ) { break;  }
//      if ( $check == true ){$next = $key+1; } else { $next = $key-1; }
//      $change = $result[$next];
//      $result[$next] = $result[$key];
//      $result[$key] = $change;
//      $key = $next;
//  }
    echo $step_all;

?>

<?php

    $file = file('php://stdin');
    $n = $file[0];
    $solds = explode(' ', $file[1]);

    $result = preg_split('/ /',$file[1]);
    $min = min($result);
    $max = max($result);
    $key_min = array_search($min, $result);
    $key_max = array_search($max, $result);
    $step_max = $key_max - 1;
    $step_min = $n - $key_min;
    if ( $key_max>$key_min ) { $step_min = $step_min-1;}
    $step_all = $step_max+$step_min;
    for ($i = 0; $i < $step_all; $i++)
    {
        if (!isset($key)) {$key = $key_max; $check = false;}
        if ($key == 0 AND $check == false) { $key = array_search($min, $result); $check = true; }
        if ( $result[0] ==$max AND $result[$n-1]==$min ) { break;  }
        if ( $check == true ){$next = $key+1; } else { $next = $key-1; }
        $change = $result[$next];
        $result[$next] = $result[$key];
        $result[$key] = $change;
        $key = $next;
    }
    echo $step_all;

?>

<?php

    $file = file('php://stdin');
    $n = intval($file[0]);
    $result = explode(" ",trim($file[1]));
    $max =  array_search(max($result), $$result);
    $min = array_keys($result, min($result));
    $min=$min[count($min)-1];
    $step= $max+$n-$min;
    if ( $max>$min ) $step--;
    echo $step;

?>

<?php

    $n = $file[0];
    $solds = explode(' ', $file[1]);

    $result = preg_split('/ /',$file[1]);
    $min = min($result);
    $max = max($result);
    $key_min = array_search($min, $result);
    $key_max = array_search($max, $result);
    $step_max = $key_max - 1;
    $step_min = $n - $key_min;
    if ( $key_max>$key_min ) { $step_min = $step_min-1;}
    $step_all = $step_max+$step_min;
    for ($i = 0; $i < $step_all; $i++)
    {
        if (!isset($key)) {$key = $key_max; $check = false;}
        if ($key == 0 AND $check == false) { $key = array_search($min, $result); $check = true; }
        if ( $result[0] ==$max AND $result[$n-1]==$min ) { break;  }
        if ( $check == true ){$next = $key+1; } else { $next = $key-1; }
        $change = $result[$next];
        $result[$next] = $result[$key];
        $result[$key] = $change;
        $key = $next;
    }
    echo $step_all;

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
   $result = preg_split('/ /',$file[1]);
   $min = max(array_keys($result, min($result)));
   $max = min(array_keys($result, max($result)));
   $step = ($key_max - 1) + ($n - $key_min);
   if ( $max>$min ) { $step = $step-1;}
   var_dump ($step, $max, $min);

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
   $result = explode(' ',$file[1]);
   $min = max(array_keys($result, min($result)));
   $max = min(array_keys($result, max($result)));
   $step = $key_max - 1 + $n - $key_min;
   if ( $max>$min ) { $step = $step-1;}
   echo sprintf('%.0f', $step);

?>

<?php

    $file = file('php://stdin');
    $n = intval($file[0]);
    $result = explode(" ",trim($file[1]));
    $max =  array_search(max($result), $$result);
    $min = array_keys($result, min($result));
    $min=$min[count($min)-1];
    $step= $max+$n-$min-1;
    if ( $max>$min ) $step--;
    echo $step;

?>

<?php

    $file = file('php://stdin');
    $n = $file[0];
    $result = preg_split('/ /',$file[1]);
    $min = min($result);
    $max = max($result);
    $key_min = max(array_keys( $result, $min));
    $key_max = min(array_keys($result, $max));
    $step_max = $key_max - 1;
    $step_min = $n - $key_min;
    if ( $key_max>$key_min ) { $step_min = $step_min-1;}
    $step_all = $step_max+$step_min;
    echo $step_all;

?>

<?php

    $n = rand(2, 100);
    settype($rost, "string");
    for ($i = 1; $i <= $n; $i++)
        {
            if ( $i == 1 ) {$rost.= rand(1, 100);}
            else { $rost.= ' '.rand(1, 100);}
        }

    $result = preg_split('/ /',$rost);
    $min = min($result);
    $max = max($result);
    $key_min = array_search($min, $result);
    $key_max = array_search($max, $result);
    $step_max = $key_max - 1;
    $step_min = $n - $key_min;
    if ( $key_max>$key_min ) { $step_min = $step_min-1;}
    $step_all = $step_max+$step_min;
    for ($i = 0; $i < $step_all; $i++)
    {
        if (!isset($key)) {$key = $key_max; $check = false;}
        if ($key == 0 AND $check == false) { $key = array_search($min, $result); $check = true; }
        if ( $result[0] ==$max AND $result[$n-1]==$min ) { break;  }
        if ( $check == true ){$next = $key+1; } else { $next = $key-1; }
        $change = $result[$next];
        $result[$next] = $result[$key];
        $result[$key] = $change;
        $key = $next;
    }
    echo $step_all;

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];

   $result = preg_split('/ /',$file[1]);

   $min = max(array_keys($result, min($result)));
   $max = min(array_keys($result, max($result)));
   $step = ($key_max - 1) + ($n - $key_min);
   if ( $max>$min ) { $step = $step-1;}
   print_r ( $step);

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
//       $n = 3;
//       $file[1] = "1 2 1";
   $result = preg_split('/ /',$file[1]);
   if ( $result[0] ==max($result) AND $result[$n-1]==min($result))
   {
    echo "0";
   }
   else {

    echo $kmin = max(array_keys($result, min($result)));
    echo $kmax = min(array_keys($result, max($result)));
    echo $step = ($kmax - 1) + ($n - $kmin);
    if ( $kmax>$kmin ) { $step = $step-1;}
    print_r ( $step);
   }
?>

<?php
   $n = 5;
   $file[1] = "100 95 100 100 88";
   $result = preg_split('/ /',$file[1]);
   $key_min = max(array_keys($result, min($result)));
   $key_max = min(array_keys($result, max($result)));
   $step = ($key_max - 1) + ($n - $key_min);
   if ( $key_max>$key_min ) { $step = $step-1;}
   echo $step;

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
//       $n = 5;
//       $file[1] = "100 95 100 100 88";
   $result = preg_split('/ /',$file[1]);
   if ( $result[0] !=max($result) AND $result[$n-1]!=min($result))
   {
   $key_min = max(array_keys($result, min($result)));
   $key_max = min(array_keys($result, max($result)));
   $step = ($key_max - 1) + ($n - $key_min);
   if ( $key_max>$key_min ) { $step = $step-1;}
   print_r ( $step);
   }
   else {
    echo "0";
   }
?>

<?php

//   $file = file('php://stdin');
//   $n = $file[0];
       $n = 5;
       $file[1] = "100 95 100 100 88";
   $result = preg_split('/ /',$file[1]);
   $key_min = max(array_keys($result, min($result)));
   $key_max = min(array_keys($result, max($result)));
   $step = ($key_max - 1) + ($n - $key_min);
   if ( $key_max>$key_min ) { $step = $step-1;}
   var_dump($step);
   //echo $step;

?>

<?php

   $file = file('php://stdin');
   $n = $file[0];
   $result = explode(' ',$file[1]);
   if ( $result[0] !=max($result) AND $result[$n-1]!=min($result))
    {

   $min = max(array_keys($result, min($result)));
   if (min($result)==$result[$n-1]) {$min = $n-1;}
   $max = min(array_keys($result, max($result)));
   $step = $max - 1 + $n - $min;
   if ( $max>$min ) { $step = $step-1;}
   echo $step;
       }
       else  {echo "0"; }

?>


There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.Your task is to determine the minimum number of rooms needed to hold classes for all groups on Monday. Note that one room can hold at most one group class in a single time slot.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of groups.  Each of the following n lines contains a sequence consisting of 7 zeroes and ones — the schedule of classes on Monday for a group. If the symbol in a position equals to 1 then the group has class in the corresponding time slot. In the other case, the group has no class in the corresponding time slot.

Print minimum number of rooms needed to hold all groups classes on Monday.

NoteIn the first example one room is enough. It will be occupied in each of the seven time slot by the first group or by the second group.In the second example three rooms is enough, because in the seventh time slot all three groups have classes.

<?php
$console = fopen("php://stdin", "r");

$n = +fgets($console);

$couplesNum = 7;
$sumOfCouples = array_fill(0, $couplesNum, 0);
for ($i = 0; $i < $n; ++$i)
{
  $groupCouple = array_map('intval', str_split(fgets($console)));
  for ($j = 0; $j < $couplesNum; ++$j)
  {
    $sumOfCouples[$j] += $groupCouple[$j];
  }
}

fclose($console);

print max($sumOfCouples);


You are given a huge decimal number consisting of $$$n$$$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.You are also given two integers $$$0 \le y < x < n$$$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.

The first line of the input contains three integers $$$n, x, y$$$ ($$$0 \le y < x < n \le 2 \cdot 10^5$$$) — the length of the number and the integers $$$x$$$ and $$$y$$$, respectively. The second line of the input contains one decimal number consisting of $$$n$$$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.

Print one integer — the minimum number of operations you should perform to obtain the number having remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.

NoteIn the first example the number will be $$$11010100100$$$ after performing one operation. It has remainder $$$100$$$ modulo $$$100000$$$.In the second example the number will be $$$11010100010$$$ after performing three operations. It has remainder $$$10$$$ modulo $$$100000$$$.

<?php
# 1165A
declare(strict_types=1);

$start = microtime(true);
$stdin = STDIN;
[$n, $x, $y] = fscanf($stdin, '%u %u %u');

$xi = $n - $x - 1;
$yi = $n - $y - 1;

$result = 0;

$digit = trim(fgets($stdin));

for ($i = $n -1; $i > $xi; $i--) {
    if ((($i > $yi) || ($i > $xi && $i < $yi)) && $digit[$i] === '1') {
        $result++;
    } elseif($i === $yi && $digit[$i] === '0') {
        $result++;
    }
}

echo $result;

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

    $a1 = explode(" ", $s1);
    $n = $a1[0];
    $x = $a1[1];
    $y = $a1[2];

    $iteration = 0;
    if ( bcmod ($s,bcpow(10, $x)) == bcpow (10, $y)) {
        echo $iteration;
        exit;
    }

    for ($i=$n-1; $i >= 0; $i--) {
        if($s[$i] == 0) {
            $s[$i] = 1;
        } else {
            $s[$i] = 0;
        }
        $iteration++;
        if ( bcmod ($s,bcpow(10, $x)) == bcpow (10, $y)) {
            echo $iteration;
            exit;
        }
    }

?>


One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 ≤ i ≤ k) child wrote the number ai (1 ≤ ai ≤ n·k). All numbers ai accidentally turned out to be different.Now the children wonder, how to divide the orange so as to meet these conditions:  each child gets exactly n orange segments;  the i-th child gets the segment with number ai for sure;  no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.

The first line contains two integers n, k (1 ≤ n, k ≤ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 ≤ ai ≤ n·k), where ai is the number of the orange segment that the i-th child would like to get. It is guaranteed that all numbers ai are distinct.

Print exactly n·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces. You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = range(1, $a * $b);
array_unshift($d, " ");
unset($d[0]);
for($x = 0; $x < $b; $x++)
{
    $e = array_search($c[$x], $d);
    unset($d[$e]);
}
sort($d);
for($x = 0; $x < $b; $x++)
{
    if($x == $b - 1)
    {
        print $c[$x] . " " . implode(" ", array_slice($d, 0, $a - 1));
        array_splice($d, 0, $a - 1);
    }
    else
    {
        print $c[$x] . " " . implode(" ", array_slice($d, 0, $a - 1)) . "\n";
        array_splice($d, 0, $a - 1);
    }
}
?>

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

// Codeforces Contest 150 Div 2 Problem A
$raw = g();
$n = $raw[0];
$k = $raw[1];
$raw = g();
for ($i = 1; $i <= $n * $k; $i++) {
	$num[$i] = false;
}
for ($i = 1; $i <= $k; $i++) {
	$ai[$i] = $raw[$i-1];
	$num[$ai[$i]] = true;
	$res[$i] = "";
}

$ct = 0;
$person = 1;
for ($i = 1; $i <= $n * $k; $i++) {
	if (!$num[$i]) {
		$ct++;
		$res[$person] .= $i . " ";
		if ($ct == $n-1) {
			$ct = 0;
			$person++;
		}
	}
}
for ($i = 1; $i <= $k; $i++) {
	echo $res[$i] . $ai[$i] . "\n";
}

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

<?PHP
$nk = explode(" ",trim(fgets(STDIN)));
$ld = explode(" ",trim(fgets(STDIN)));
arsort($ld);
$nkm = $nk[0]*$nk[1];
for($i=1;$i<=$nk[1]; $i++)
{
    for($b=1;$b<=$nk[0]-1; $b++)
    {
        while(in_array($nkm,$ld)){
        $nkm--;
        }
        echo $nkm.' ';
        $nkm--;
    }
    echo $ld[$i-1].PHP_EOL;

}
?>


Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?

The first line of input contains an integer t (0 < t < 180) — the number of tests. Each of the following t lines contains a single integer a (0 < a < 180) — the angle the robot can make corners at measured in degrees.

For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible.

NoteIn the first test case, it is impossible to build the fence, since there is no regular polygon with angle .In the second test case, the fence is a regular triangle, and in the last test case — a square.

<?php

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

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

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

    $x = trim(fgets($f));
    $n = 360/(180-$x);

    if (round($n)!=$n) echo "NO\n";
    else echo "YES\n";

}

<?php
// 270A     Завидный забор
$in = fopen("php://stdin", 'r');

$input_line = fgets($in);
// list($a, $b, $s) = preg_split('/ /', substr($input_line, 0, strlen($input_line)-2), -1, PREG_SPLIT_NO_EMPTY);

$n = (int) $input_line;

for ($i=0; $i < $n; $i++) {
    $input_line = fgets($in);
    $a = (int) $input_line;
    if ((360 % (180 -$a)) == 0) {
        echo "YES\n";
    } else {
        echo "NO\n";
    }
}

?>

<?// BismiLahi Rahmani Rahim ?>

<?php

fscanf(STDIN, "%d", $ntest);

for ($i = 0; $i < $ntest; $i ++) {
	fscanf(STDIN, "%d", $a);
	printf("%s\n", 360%(180 - $a) == 0 ? "YES" : "NO");
}

?>

<?PHP
$var = trim(fgets(STDIN));
while($var>0){
$n = trim(fgets(STDIN));
if(is_integer((360/(180-$n)))){
echo "YES".PHP_EOL;}
else{ echo "NO".PHP_EOL;}
$var--;
}

<?php
$n=trim(fgets(STDIN));
while($n-->0){
  $a=trim(fgets(STDIN));
  $b=180-$a;
  if(360%$b==0)
    print "YES\n";
  else {
    print "NO\n";
  }
}
?>

<?PHP
$t = trim(fgets(STDIN));
for($i = 0; $i < $t; $i ++)
{
    $n = trim(fgets(STDIN));
   if ((360%(180-$n)) == 0)
    {
        echo "YES".PHP_EOL;
    }
    else echo "NO".PHP_EOL;
}

<?php
$t=trim(fgets(STDIN));
while($t>0){
	$n=trim(fgets(STDIN));
	if(is_integer(360/(180-$n))){
		echo "YES";
	}
	else echo "NO";
	echo PHP_EOL;
	$t--;
}
?>

<?php
error_reporting("off");
//270A: Fancy Fence
$t = trim(fgets(STDIN));
$result = "";
for ($i = 0; $i < $t; $i++) {
    $angle = trim(fgets(STDIN));
    $extAngle = 180 - $angle;
    if (360 % $extAngle == 0) {
        $result .="YES\n";
    } else {
        $result .= "NO\n";
    }
}
echo $result;
?>

<?php
// 270A     Завидный забор
$in = fopen("php://stdin", 'r');

$input_line = fgets($in);
// list($a, $b, $s) = preg_split('/ /', substr($input_line, 0, strlen($input_line)-2), -1, PREG_SPLIT_NO_EMPTY);

$n = (int) $input_line;

for ($i=0; $i < $n; $i++) {
    $input_line = fgets($in);
    $a = (int) $input_line;
    if ((360 % (180 -$a)) == 0) {
        echo "YES";
    } else {
        echo "NO";
    }
}

?>

<?PHP
$var = trim(fgets(STDIN));
while($var>0){
$n = trim(fgets(STDIN));
if(is_integer((360/(180-$n)))){
echo "YES";}
else{ echo "NO";}
$var--;
}

<?php
$n=trim(fgets(STDIN));
while($n-->0){
  $a=trim(fgets(STDIN));
  if($a>=60)
    echo "YES\n";
  else {
    echo "NO\n";
  }
}
?>

<?php
error_reporting("off");
//270A: Fancy Fence
$t = trim(fgets(STDIN));
$result = "";
for ($i = 0; $i < $t; $i++) {
    $angle = trim(fgets(STDIN));
    $extAngle = 180 - $angle;
    $sides = 369 / $extAngle;
    if (is_int((int)$sides)) {
        $result .="YES\n";
    } else {
        $result .= "NO\n";
    }
}
echo substr($result, 0, -2);
?>

<?php
error_reporting("off");
//270A: Fancy Fence
$t = trim(fgets(STDIN));
$result = "";
for ($i = 0; $i < $t; $i++) {
    $angle = trim(fgets(STDIN));
    $extAngle = 180 - $angle;
    $sides = 369 / $extAngle;
    if (is_int($sides)) {
        $result .="YES\n";
    } else {
        $result .= "NO\n";
    }
}
echo substr($result, 0, -2);
?>

<?php
error_reporting("off");
//270A: Fancy Fence
$t = trim(fgets(STDIN));
$result = "";
for ($i = 0; $i < $t; $i++) {
    $angle = trim(fgets(STDIN));
    $extAngle = 180 - $angle;
    $sides = 369 / $extAngle;
    if (is_int((int)$sides)) {
        $result .="YES\n";
    } else {
        $result .= "NO\n";
    }
}
echo substr($result, 0, -1);
?>


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i. e. change $$$x \to (-x)$$$). What is the maximum number of different values in the array you can achieve?

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The next lines contain the description of the $$$t$$$ test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 100$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$).

For each test case, print one integer: the maximum number of different elements in the array that you can achieve negating numbers in the array.

NoteIn the first example we can, for example, negate the first and the last numbers, achieving the array $$$[-1, 1, 2, -2]$$$ with four different values.In the second example all three numbers are already different.In the third example negation does not change anything.

<?php
$t = fgets(STDIN);
while ($t-- && fgets(STDIN)) {
    $a = array_map('abs', fgetcsv(STDIN, 0, ' '));
    $a1 = array_flip($a);
    $a2 = array_filter(array_diff_key($a, array_flip($a1)));
    printf("%d\n", count($a1) + count(array_unique($a2)));
}

<?php
$t = fgets(STDIN);
while ($t-- && fgets(STDIN)) {
    $a = fgetcsv(STDIN, 0, ' ');
    $a1 = array_flip($a);
    $a2 = array_filter(array_diff_key($a, array_flip($a1)));
    printf("%d\n", count($a1) + count(array_unique($a2)));
}


While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1, a2, ..., am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1, f2, ..., fn of length n and for each number ai got number bi = fai. To finish the prank he erased the initial sequence ai.It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the lengths of sequences fi and bi respectively. The second line contains n integers, determining sequence f1, f2, ..., fn (1 ≤ fi ≤ n). The last line contains m integers, determining sequence b1, b2, ..., bm (1 ≤ bi ≤ n).

Print "Possible" if there is exactly one sequence ai, such that bi = fai for all i from 1 to m. Then print m integers a1, a2, ..., am. If there are multiple suitable sequences ai, print "Ambiguity". If Spongebob has made a mistake in his calculations and no suitable sequence ai exists, print "Impossible".

NoteIn the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique.In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence.In the third sample fi ≠ 3 for all i, so no sequence ai transforms into such bi and we can say for sure that Spongebob has made a mistake.


One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?He needs your help to check it.A Minesweeper field is a rectangle $$$n \times m$$$, where each cell is either empty, or contains a digit from $$$1$$$ to $$$8$$$, or a bomb. The field is valid if for each cell:   if there is a digit $$$k$$$ in the cell, then exactly $$$k$$$ neighboring cells have bombs.  if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $$$8$$$ neighboring cells).

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the sizes of the field. The next $$$n$$$ lines contain the description of the field. Each line contains $$$m$$$ characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from $$$1$$$ to $$$8$$$, inclusive.

Print "YES", if the field is valid and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrarily.

NoteIn the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.You can read more about Minesweeper in Wikipedia's article.

<?php

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

fscanf($handle, "%i %i", $n, $m);

$field = [];
$bombs = [];

$totalSum = 0;

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

    $row = str_split(trim(fgets($handle)));

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

        if ($row[$j] == '*') {

            if (!isset($bombs[$i])) {
                $bombs[$i] = [];
            }

            $bombs[$i][] = $j;
        } elseif ($row[$j] != '.') {

            $row[$j] = intval($row[$j]);;
            $totalSum += $row[$j];
        }
    }

    $field[] = $row;
}

$result = 'YES';

foreach ($bombs as $row => $cols) {

    foreach ($cols as $col) {

        $numCount = 0;

        for ($i = -1; $i < 2; $i++) {

            for ($j = -1; $j < 2; $j++) {

                if ($i != 0 || $j != 0) {

                    if (isset($field[$row + $i][$col + $j])) {

                        $val = $field[$row + $i][$col + $j];

                        if ($val == '.' || ($val != '*' && $val == 0)) {

                            $result = 'NO';
                            break;
                        } elseif ($val != '*') {

                            $numCount++;
                            $field[$row + $i][$col + $j]--;
                            $totalSum--;
                        }
                    }
                }
            }
        }
    }

    if ($result == 'NO') {
        break;
    }
}

if ($totalSum != 0) {
    $result = 'NO';
}

echo $result;

<?php

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

fscanf($handle, "%i %i", $n, $m);

$field = [];
$bombs = [];

$totalSum = 0;

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

    $row = str_split(trim(fgets($handle)));

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

        if ($row[$j] == '*') {

            if (!isset($bombs[$i])) {
                $bombs[$i] = [];
            }

            $bombs[$i][] = $j;
        } elseif ($row[$j] != '.') {

            $row[$j] = intval($row[$j]);;
            $totalSum += $row[$j];
        }
    }

    $field[] = $row;
}

$result = 'YES';

foreach ($bombs as $row => $cols) {

    foreach ($cols as $col) {

        $numCount = 0;

        for ($i = -1; $i < 2; $i++) {

            for ($j = -1; $j < 2; $j++) {

                if ($i != 0 || $j != 0) {

                    if (isset($field[$row + $i][$col + $j])) {

                        $val = $field[$row + $i][$col + $j];

                        if ($val == '.' || ($val != '*' && $val == 0)) {

                            $result = 'NO';
                            break;
                        } elseif ($val != '*') {

                            $numCount++;
                            $field[$row + $i][$col + $j]--;
                            $totalSum--;
                        }
                    }

                }
            }

            if ($numCount == 0) {

                $result = 'NO';
                break;
            }
        }
    }

    if ($numCount == 0) {

        $result = 'NO';
        break;
    }
}

if ($totalSum != 0) {
    $result = 'NO';
}

echo $result;

<?php

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

fscanf($handle, "%i %i", $n, $m);

$field = [];
$bombs = [];

$totalSum = 0;

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

    $row = str_split(trim(fgets($handle)));

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

        if ($row[$j] == '*') {

            if (!isset($bombs[$i])) {
                $bombs[$i] = [];
            }

            $bombs[$i][] = $j;
        } elseif ($row[$j] != '.') {

            $row[$j] = intval($row[$j]);;
            $totalSum += $row[$j];
        }
    }

    $field[] = $row;
}

$result = 'YES';

foreach ($bombs as $row => $cols) {

    foreach ($cols as $col) {

        $numCount = 0;

        for ($i = -1; $i < 2; $i++) {

            for ($j = -1; $j < 2; $j++) {

                if ($i != 0 || $j != 0) {

                    if (isset($field[$row + $i][$col + $j])) {

                        $val = $field[$row + $i][$col + $j];

                        if ($val == '.' || ($val != '*' && $val == 0)) {

                            $result = 'NO';
                            break;
                        } elseif ($val != '*') {

                            $numCount++;
                            $field[$row + $i][$col + $j]--;
                            $totalSum--;
                        }
                    }
                }
            }
        }

        if ($numCount == 0) {

            $result = 'NO';
            break;
        }
    }

    if ($result == 'NO') {
        break;
    }
}

if ($totalSum != 0) {
    $result = 'NO';
}

echo $result;