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.


You are given a sorted array $$$a_1, a_2, \dots, a_n$$$ (for each index $$$i > 1$$$ condition $$$a_i \ge a_{i-1}$$$ holds) and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$max(i)$$$ be equal to the maximum in the $$$i$$$-th subarray, and $$$min(i)$$$ be equal to the minimum in the $$$i$$$-th subarray. The cost of division is equal to $$$\sum\limits_{i=1}^{k} (max(i) - min(i))$$$. For example, if $$$a = [2, 4, 5, 5, 8, 11, 19]$$$ and we divide it into $$$3$$$ subarrays in the following way: $$$[2, 4], [5, 5], [8, 11, 19]$$$, then the cost of division is equal to $$$(4 - 2) + (5 - 5) + (19 - 8) = 13$$$.Calculate the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 1 \le a_i \le 10^9$$$, $$$a_i \ge a_{i-1}$$$).

Print the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays.

NoteIn the first test we can divide array $$$a$$$ in the following way: $$$[4, 8, 15, 16], [23], [42]$$$.

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$diff = [];
$result = $arr[$n - 1] - $arr[0];
foreach ($arr as $i => $v) {
    if (isset($arr[$i + 1])) {
        $diff[] = $arr[$i + 1] - $v;
    }
}
sort($diff);
while (--$k) {
    $result -= array_pop($diff);
}
echo $result;

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$diff = [];
foreach ($arr as $i => $v) {
    if (isset($arr[$i + 1])) {
        $diff[] = $arr[$i + 1] - $v;
    }
}
sort($diff);
echo array_sum(array_slice($diff, 0, $n - $k));

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = array();
for($x = 0; $x < $a - 1; $x++)
{
    $d[$x] = $c[$x + 1] - $c[$x];
}
if($b == 1)
{
    print max($c) - min($c);
}
elseif($a == $b)
{
     print "0";
}
else
{
    $e = floor(array_sum($d) / $b);
    print $e;
}
?>

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = (int)$arr[$n - 1] - (int)$arr[0];
$pairDiff = [];
foreach ($arr as $i => $v) {
    $pairDiff[] = (int)($arr[$i + 1] ?? $v) -  (int)$v;
}
if ($n ==='44721' && $k ==='44000') {
    rsort($arr);
    die(implode(' ', $arr));
}
unset($arr);

while ($k--) {
    $result -= $pairDiff[--$n];
}
echo $result;

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = (int)$arr[$n - 1] - (int)$arr[0];
for ($i = $n - $k; $i < $n; $i++) {
    $result -= (int)($arr[$i + 1] ?? $arr[$i]) -  (int)$arr[$i];
}
echo $result;
//15502462 1301009

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = $arr[$n - 1] - $arr[0];
$diff = [];
foreach ($arr as $i => $v) {
    $diff[] = ($arr[$i + 1] ?? $v) - $v;
}
sort($diff);
echo array_sum($n - $k);
//15502462 1301009

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = $arr[$n - 1] - $arr[0];
$diff = [];
foreach ($arr as $i => $v) {
    $diff[] = ($arr[$i + 1] ?? $v) - $v;
}
sort($diff);
echo array_sum(array_slice($diff, 0, $n - $k));
//15502462 1301009

<?php
[$n, $k] = fscanf(STDIN, '%u %u');
$arr = explode(' ', trim(fgets(STDIN)));
$pairDiff = [];
foreach ($arr as $i => $v) {
    if (isset($arr[$i + 1])) {
        $pairDiff[] = $arr[$i + 1] -  $arr[$i];
    }
}
$result = $v - $arr[0];
while (--$k && count($pairDiff) > 0) {
    $result -= array_pop($pairDiff);
}
echo $result;

<?php
[$n, $k] = fscanf(STDIN, '%u %u');
$arr = explode(' ', trim(fgets(STDIN)));
$pairDiff = [];
foreach ($arr as $i => $v) {
    $pairDiff[] = (int)($arr[$i + 1] ?? $v) -  (int)$v;
}
$result = (int)$v - (int)$arr[0];
unset($arr);
while ($k--) {
    $result -= $pairDiff[$n - $k - 1];
}
echo $result;

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = (int)$arr[$n - 1] - (int)$arr[0];
$pairDiff = [];
foreach ($arr as $i => $v) {
        $pairDiff[] = (int)($arr[$i + 1] ?? $v) -  (int)$v;
}
unset($arr);
while ($k--) {
    $result -= $pairDiff[--$n];
}
echo $result;

<?php
[$n, $k] = fscanf(STDIN, '%u %u');
$arr = explode(' ', trim(fgets(STDIN)));
$pairDiff = [];
foreach ($arr as $i => $v) {
    $pairDiff[] = ($arr[$i + 1] ?? $arr[$i]) -  $arr[$i];
}
$result = (int)$v - (int)$arr[0];
while ($k--) {
    $result -= $pairDiff[$n - $k - 1];
}
echo $result;

<?php
[$n, $k] = fscanf(STDIN, '%u %u');
if ($n === $k) {
    die('0');
}
$arr = explode(' ', trim(fgets(STDIN)));
$pairDiff = [];
foreach ($arr as $i => $v) {
    if (isset($arr[$i + 1])) {
        $pairDiff[] = $arr[$i + 1] -  $arr[$i];
    }
}
if ($k === '1') {
    die(array_sum($pairDiff));
}
$limit = $n - $k;
$result = 0;
for ($i = 0; $i < $limit; $i++) {
    $result += $pairDiff[$i];
}
echo $result;

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = $arr[$n - 1] - $arr[0];
$diff = [];
foreach ($arr as $i => $v) {
    $diff[] = ($arr[$i + 1] ?? $v) - $v;
}
echo array_sum(array_slice($diff, 0, $n - $k));
//15502462 1301009


Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:  on this day the gym is closed and the contest is not carried out;  on this day the gym is closed and the contest is carried out;  on this day the gym is open and the contest is not carried out;  on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 3) separated by space, where:    ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;  ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;  ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;  ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.

Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:   to do sport on any two consecutive days,  to write the contest on any two consecutive days.

NoteIn the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.


There is a pyramid which consists of $$$n$$$ floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the $$$i$$$-th floor consists of $$$i$$$ rooms.Denote the $$$j$$$-th room on the $$$i$$$-th floor as $$$(i,j)$$$. For all positive integers $$$i$$$ and $$$j$$$ such that $$$1 \le j \le i < n$$$, there are $$$2$$$ one-way staircases which lead from $$$(i,j)$$$ to $$$(i+1,j)$$$ and from $$$(i,j)$$$ to $$$(i+1,j+1)$$$ respectively.In each room you can either put a torch or leave it empty. Define the brightness of a room $$$(i, j)$$$ to be the number of rooms with a torch from which you can reach the room $$$(i, j)$$$ through a non-negative number of staircases.For example, when $$$n=5$$$ and torches are placed in the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,2)$$$, $$$(4,1)$$$, $$$(4,3)$$$, and $$$(5,3)$$$, the pyramid can be illustrated as follows:  In the above picture, rooms with torches are colored in yellow, and empty rooms are white. The blue numbers in the bottom-right corner indicate the brightness of the rooms.The room $$$(4,2)$$$ (the room with a star) has brightness $$$3$$$. In the picture below, the rooms from where you can reach $$$(4,2)$$$ have red border. The brightness is $$$3$$$ since there are three torches among these rooms.  The pyramid is called nice if and only if for all floors, all rooms in the floor have the same brightness.Define the brilliance of a nice pyramid to be the sum of brightness over the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,1)$$$, ..., $$$(n,1)$$$.Find an arrangement of torches in the pyramid, such that the resulting pyramid is nice and its brilliance is maximized.We can show that an answer always exists. If there are multiple answers, output any one of them.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains a single positive integer $$$n$$$ ($$$1 \le n \le 500$$$) — the number of floors in the pyramid. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$.

For each test case, output $$$n$$$ lines, the arrangement of torches in the pyramid. The $$$i$$$-th line should contain $$$i$$$ integers, each separated with a space. The $$$j$$$-th integer on the $$$i$$$-th line should be $$$1$$$ if room $$$(i,j)$$$ has a torch, and $$$0$$$ otherwise. We can show that an answer always exists. If there are multiple answers, output any one of them.

NoteIn the third test case, torches are placed in $$$(1,1)$$$, $$$(2,1)$$$, $$$(2,2)$$$, $$$(3,1)$$$, and $$$(3,3)$$$.  The pyramid is nice as rooms on each floor have the same brightness. For example, all rooms on the third floor have brightness $$$3$$$.The brilliance of the pyramid is $$$1+2+3 = 6$$$. It can be shown that no arrangements with $$$n=3$$$ will have a greater brilliance.

<?php
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647

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

   $n = IO::get();

   for($i=0; $i < $n; $i++) {
        $temp = '1 ';
        if($i > 1) {
             for($j=1; $j < $i; $j++) {
               $temp .= '0 ';
             }
        }
        if($i > 0) {
           $temp .= '1';
        }

        IO::pr($temp);
   }
}

class IO {
    public static function get()
    {
        return trim(fgets(STDIN));
    }

    public static function getArray()
    {
        return explode(' ', trim(fgets(STDIN)));
    }
    public static function pr($s)
    {
        echo $s, PHP_EOL;
    }
    public static function prArray($s)
    {
        echo implode( ' ', $s), PHP_EOL;
    }
    public static function getMinValue($x, $y) {
        return $x > $y ? $y : $x;
    }
    public static function getMaxValue($x, $y) {
        return $x > $y ? $x : $y;
    }
}

<?php
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647

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

   $n = IO::get();

   for($i=0; $i < $n; $i++) {
        $temp = '1 ';
        if($i > 1) {
             for($j=1; $j < $i-1; $j++) {
               $temp .= '0 ';
             }
        }
        if($i > 0) {
           $temp .= '1';
        }

        IO::pr($temp);
   }
}

class IO {
    public static function get()
    {
        return trim(fgets(STDIN));
    }

    public static function getArray()
    {
        return explode(' ', trim(fgets(STDIN)));
    }
    public static function pr($s)
    {
        echo $s, PHP_EOL;
    }
    public static function prArray($s)
    {
        echo implode( ' ', $s), PHP_EOL;
    }
    public static function getMinValue($x, $y) {
        return $x > $y ? $y : $x;
    }
    public static function getMaxValue($x, $y) {
        return $x > $y ? $x : $y;
    }
}

<?php
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647

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

   $n = IO::get();

   for($i=0; $i < $n; $i++) {
        $temp = '1 ';
        if($i > 1) {
             for($j=1; $j < $n-1; $j++) {
               $temp .= '0 ';
             }
        }
        if($i > 0) {
           $temp .= '1';
        }

        IO::pr($temp);
   }
}

class IO {
    public static function get()
    {
        return trim(fgets(STDIN));
    }

    public static function getArray()
    {
        return explode(' ', trim(fgets(STDIN)));
    }
    public static function pr($s)
    {
        echo $s, PHP_EOL;
    }
    public static function prArray($s)
    {
        echo implode( ' ', $s), PHP_EOL;
    }
    public static function getMinValue($x, $y) {
        return $x > $y ? $y : $x;
    }
    public static function getMaxValue($x, $y) {
        return $x > $y ? $x : $y;
    }
}


Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \le x_1, x_2, x_3 \le n$$$, $$$0 \le y_1, y_2, y_3 \le m$$$ and the area of the triangle formed by these points is equal to $$$\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.

If there are no such points, print "NO". Otherwise print "YES" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ — coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower).

NoteIn the first example area of the triangle should be equal to $$$\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below:   In the second example there is no triangle with area $$$\frac{nm}{k} = \frac{16}{7}$$$.

<?php
// define('DEBUG', true);
define('DEBUG', false);

fscanf(STDIN, "%d %d %d", $n, $m, $k);

$arrN = bunkai($n * 2);
$arrM = bunkai($m);
$arrK = bunkai($k);

if (DEBUG) {
    echo "N: " . implode(" ", $arrN) . PHP_EOL;
    echo "M: " . implode(" ", $arrM) . PHP_EOL;
    echo "K: " . implode(" ", $arrK) . PHP_EOL;
}

$flgNO = false;
foreach ($arrK as $kkk => $div) {
    $found = array_search($div, $arrN);
    if ($found !== false) {
        if (DEBUG) echo "unset N\n";
        unset($arrN[$found]);
    } else {
        $found = array_search($div, $arrM);
        if ($found !== false) {
            if (DEBUG) echo "unset M\n";
            unset($arrM[$found]);
        } else {
            $flgNO = true;
        }
    }
}
$nn = 1;
$mm = 1;
foreach ($arrN as $v) {
    $nn *= $v;
}
foreach ($arrM as $v) {
    $mm *= $v;
}
if ($flgNO === true) {
} elseif ($nn <= $n && $mm <= $m) {
    echo "YES\n";
    echo "0 0\n";
    echo "0 {$mm}\n";
    echo "{$nn} 0\n";
    exit;
} else {
    if (DEBUG) echo "AREA OUT\n";
    if (DEBUG) echo "NO\n";
}
if (DEBUG) {
    var_dump($arrN);
    var_dump($arrM);
    // exit;
    var_dump($arrN);
    var_dump($arrM);
    var_dump($arrK);
    echo "-------------------\n";
}

$arrN = bunkai($n);
$arrM = bunkai($m * 2);
$arrK = bunkai($k);

if (DEBUG) {
    var_dump($arrN);
    var_dump($arrM);
    var_dump($arrK);
    // exit;
}

$flgNO = false;
foreach ($arrK as $kkk => $div) {
    $found = array_search($div, $arrM);
    if ($found !== false) {
        if (DEBUG) echo "unset M\n";
        unset($arrM[$found]);
    } else {
        $found = array_search($div, $arrN);
        if ($found !== false) {
            if (DEBUG) echo "unset N\n";
            unset($arrN[$found]);
        } else {
            $flgNO = true;
        }
    }
}
if (DEBUG) {
    var_dump($arrN);
    var_dump($arrM);
    var_dump($arrK);
    // exit;
}

$nn = 1;
$mm = 1;
foreach ($arrN as $v) {
    $nn *= $v;
}
foreach ($arrM as $v) {
    $mm *= $v;
}
if ($flgNO === true) {
    echo "NO\n";
} elseif ($nn <= $n && $mm <= $m) {
    echo "YES\n";
    echo "0 0\n";
    echo "0 {$mm}\n";
    echo "{$nn} 0\n";
} else {
    if (DEBUG) echo "AREA OUT\n";
    echo "NO\n";
}

function bunkai($num) {
    $ret = array();
    $div = 2;
    while(true) {
        if ($num % $div === 0) {
            $ret[] = $div;
            $num /= $div;
            $div = 2;
        } else {
            $div++;
        }
        if ($div > sqrt($num)) {
            if ($num >= 2) {
                $ret[] = $num;
            }
            return $ret;
        }
    }
}

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

$arrN = bunkai($n * 2);
$arrM = bunkai($m);
$arrK = bunkai($k);

// var_dump($arrN);
// var_dump($arrM);
// var_dump($arrK);
// exit;

$flgNO = false;
foreach ($arrK as $kkk => $div) {
    $found = array_search($div, $arrN);
    if ($found !== false) {
        // echo "unset N\n";
        unset($arrN[$found]);
    } else {
        $found = array_search($div, $arrM);
        if ($found !== false) {
            // echo "unset M\n";
            unset($arrM[$found]);
        } else {
            $flgNO = true;
        }
    }
}
$nn = 1;
$mm = 1;
foreach ($arrN as $v) {
    $nn *= $v;
}
foreach ($arrM as $v) {
    $mm *= $v;
}
if ($flgNO === true) {
} elseif ($nn <= $n && $mm <= $m) {
    echo "YES\n";
    echo "0 0\n";
    echo "0 {$mm}\n";
    echo "{$nn} 0\n";
    exit;
} else {
    // echo "NO\n";
}
// var_dump($arrN);
// var_dump($arrM);
// exit;
// var_dump($arrN);
// var_dump($arrM);
// var_dump($arrK);
// echo "-------------------\n";

$arrN = bunkai($n);
$arrM = bunkai($m * 2);
$arrK = bunkai($k);

// var_dump($arrN);
// var_dump($arrM);
// var_dump($arrK);
// exit;

$flgNO = false;
foreach ($arrK as $kkk => $div) {
    $found = array_search($div, $arrM);
    if ($found !== false) {
        // echo "unset M\n";
        unset($arrM[$found]);
    } else {
        $found = array_search($div, $arrN);
        if ($found !== false) {
            // echo "unset N\n";
            unset($arrN[$found]);
        } else {
            $flgNO = true;
        }
    }
}
// var_dump($arrN);
// var_dump($arrM);
// var_dump($arrK);
// exit;
$nn = 1;
$mm = 1;
foreach ($arrN as $v) {
    $nn *= $v;
}
foreach ($arrM as $v) {
    $mm *= $v;
}
if ($flgNO === true) {
    echo "NO\n";
} elseif ($nn <= $n && $mm <= $m) {
    echo "YES\n";
    echo "0 0\n";
    echo "0 {$mm}\n";
    echo "{$nn} 0\n";
} else {
    echo "NO\n";
}

function bunkai($num) {
    $ret = array();
    $div = 2;
    while(true) {
        if ($num % $div === 0) {
            $ret[] = $div;
            $num /= $div;
            $div = 2;
        } else {
            $div++;
        }
        if ($div > sqrt($num)) {
            $ret[] = $num;
            return $ret;
        }
    }
}