You are given a string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters and an integer number $$$k$$$.Let's define a substring of some string $$$s$$$ with indices from $$$l$$$ to $$$r$$$ as $$$s[l \dots r]$$$.Your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ positions $$$i$$$ such that $$$s[i \dots i + n - 1] = t$$$. In other words, your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$.It is guaranteed that the answer is always unique.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 50$$$) — the length of the string $$$t$$$ and the number of substrings. The second line of the input contains the string $$$t$$$ consisting of exactly $$$n$$$ lowercase Latin letters.

Print such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$. It is guaranteed that the answer is always unique.


You had $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ arranged in a circle. For each pair of neighboring numbers ($$$a_1$$$ and $$$a_2$$$, $$$a_2$$$ and $$$a_3$$$, ..., $$$a_{n - 1}$$$ and $$$a_n$$$, and $$$a_n$$$ and $$$a_1$$$), you wrote down: are the numbers in the pair equal or not.Unfortunately, you've lost a piece of paper with the array $$$a$$$. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array $$$a$$$ which is consistent with information you have about equality or non-equality of corresponding pairs?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ cases follow. The first and only line of each test case contains a non-empty string $$$s$$$ consisting of characters E and/or N. The length of $$$s$$$ is equal to the size of array $$$n$$$ and $$$2 \le n \le 50$$$. For each $$$i$$$ from $$$1$$$ to $$$n$$$:    if $$$s_i =$$$ E then $$$a_i$$$ is equal to $$$a_{i + 1}$$$ ($$$a_n = a_1$$$ for $$$i = n$$$);  if $$$s_i =$$$ N then $$$a_i$$$ is not equal to $$$a_{i + 1}$$$ ($$$a_n \neq a_1$$$ for $$$i = n$$$).

For each test case, print YES if it's possible to choose array $$$a$$$ that are consistent with information from $$$s$$$ you know. Otherwise, print NO. It can be proved, that if there exists some array $$$a$$$, then there exists an array $$$a$$$ of positive integers with values less or equal to $$$10^9$$$.

NoteIn the first test case, you can choose, for example, $$$a_1 = a_2 = a_3 = 5$$$.In the second test case, there is no array $$$a$$$, since, according to $$$s_1$$$, $$$a_1$$$ is equal to $$$a_2$$$, but, according to $$$s_2$$$, $$$a_2$$$ is not equal to $$$a_1$$$.In the third test case, you can, for example, choose array $$$a = [20, 20, 4, 50, 50, 50, 20]$$$.In the fourth test case, you can, for example, choose $$$a = [1, 3, 3, 7]$$$.

<?php

$max = 1;
$inputs = [];
for ($i = 0; $i < $max; $i++) {
    if ($i == 0) {
        $max = readline() + 1;
        continue;
    }

    $inputs[] = readline();
}

foreach ($inputs as $input) {
    if ( substr_count($input, "N") == 1 ) {
        print "NO\n";
    } else {
        print "YES\n";
    }
}

?>

<?php
$max = 1;
$inputs = [];
for ($i = 0; $i < $max; $i++) {
    if ($i == 0) {
        $max = readline() + 1;
        continue;
    }

    $inputs[] = readline();
}

foreach ($inputs as $input) {
    $start = substr($input, 0, 1);
    $end = substr($input, -1);
    if ( $start == $end ) {
        if ( $start == "E" && substr_count($input, "N") > 0 && substr_count($input, "N") % 2 == 0 ) {
            print "NO\n";
        } else {
            print "YES\n";
        }
    } else {
        print "NO\n";
    }
}

?>

<?php
$max = 1;
$inputs = [];
for ($i = 0; $i < $max; $i++) {
    if ($i == 0) {
        $max = readline() + 1;
        continue;
    }

    $inputs[] = readline();
}

foreach ($inputs as $input) {
    if ( substr($input, 0, 1) == substr($input, -1) ) {
        print "YES\n";
    } else {
        print "NO\n";
    }
}

?>


You are given a sequence $$$a$$$, initially consisting of $$$n$$$ integers.You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).To achieve this, you choose some integer $$$x$$$ that occurs at least once in $$$a$$$, and then perform the following operation any number of times (possibly zero): choose some segment $$$[l, r]$$$ of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains $$$x$$$. More formally, you choose some contiguous subsequence $$$[a_l, a_{l + 1}, \dots, a_r]$$$ such that $$$a_i \ne x$$$ if $$$l \le i \le r$$$, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the $$$(r+1)$$$-th is now $$$l$$$-th, the element that was $$$(r+2)$$$-th is now $$$(l+1)$$$-th, and so on (i. e. the remaining sequence just collapses).Note that you can not change $$$x$$$ after you chose it.For example, suppose $$$n = 6$$$, $$$a = [1, 3, 2, 4, 1, 2]$$$. Then one of the ways to transform it in two operations is to choose $$$x = 1$$$, then:  choose $$$l = 2$$$, $$$r = 4$$$, so the resulting sequence is $$$a = [1, 1, 2]$$$;  choose $$$l = 3$$$, $$$r = 3$$$, so the resulting sequence is $$$a = [1, 1]$$$. Note that choosing $$$x$$$ is not an operation. Also, note that you can not remove any occurrence of $$$x$$$.Your task is to find the minimum number of operations required to transform the sequence in a way described above.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.

<?php
fscanf(STDIN, "%d", $t);
while ($t--) {
    fscanf(STDIN, "%d", $n);
    $arr = explode(' ', trim(fgets(STDIN)));
    $path = [$arr[0] => 1];
    $prev_value = $arr[0];
    for ($i = 1; $i < $n; $i++) {
        if ($arr[$i] != $prev_value) {
            isset($path[$arr[$i]]) or $path[$arr[$i]] = 0;
            $path[$arr[$i]] += 1;
            $prev_value = $arr[$i];
        }
    }
    $a = $arr[0];
    $b = $arr[$n-1];
    $arr = array_diff($arr, [$a, $b]);
    ($a == $b) and $path[$a] -= 1;
    foreach (array_unique($arr) as $value) {
        $path[$value] += 1;
    }
    printf("%d\n", min($path) ?? 0);
}

<?php
$t = trim(fgets(STDIN));

while ($t--) {
    $n = trim(fgets(STDIN));
    $s = trim(fgets(STDIN));
    $a = preg_split("/[\s,]+/", $s);
    $ex = []; $bAll = true;
    for ($i = 0; $i < ($n-1); $i++) {
        if ($a[$i] != $a[$i+1]) {
            $bAll = false;
        }
        if (isset($ex[$a[$i]])) {
            if ($a[$i] != $a[$i+1]) {
                $ex[$a[$i]] = $ex[$a[$i]] + 1;
            }
        } else {
            $ex[$a[$i]] = 0;
        }
    }

    if ($bAll) {
        echo "0\n";
    } else {
        foreach($ex as $sValue => $iCount) {
            if ($a[$n-1] == $sValue && $sValue == $a[0]) {
                $ex[$sValue] = $ex[$sValue] + 1;
            }
            if ($a[$n-1] != $sValue) {
                $ex[$sValue] = $ex[$sValue] + 1;
            }
            if ($a[0] != $sValue) {
                $ex[$sValue] = $ex[$sValue] + 1;
            }
        }
        echo min($ex)."\n";
    }

}

<?php
$t = trim(fgets(STDIN));

while ($t--) {
    $n = trim(fgets(STDIN));
    $s = trim(fgets(STDIN));
    $a = preg_split("/[\s,]+/", $s);
    $ex = []; $bStatus = true;
    for ($i = 0; $i < ($n - 1); $i++) {
        if ($a[$i] != $a[$i+1]) {
            $bStatus = false;
        }
        if (isset($ex[$a[$i]])) {
            if ($a[$i] != $a[$i+1]) {
                $ex[$a[$i]] = $ex[$a[$i]] + 1;
            }
        } else {
            $ex[$a[$i]] = 1;
        }
    }
    foreach ($ex as $sKey => $sValue) {
        if ($a[$n-1] != $sKey) {
            $ex[$sKey] = $sValue + 1;
        }
    }

    echo $bStatus ? 0 : min($ex);
    echo "\n";
}

<?php
$t = trim(fgets(STDIN));

while ($t--) {
    $n = trim(fgets(STDIN));
    $s = trim(fgets(STDIN));
    $a = preg_split("/[\s,]+/", $s);
    $ex = [];
    $bAll = true;
    for ($i = 1; $i < $n; $i++) {
        if ($a[$i] != $a[$i-1]) {
            $bAll = false;
        }
        if (isset($ex[$a[$i]])) {
            if ($a[$i] != $a[$i-1]) {
                $ex[$a[$i]] = $ex[$a[$i]] + 1;
            }
        } else {
            $ex[$a[$i]] = 0;
        }
    }

    if ($bAll) {
        echo "0\n";
    } else {
        foreach($ex as $sValue => $iCount) {
            if ($a[$n-1] == $sValue && $sValue == $a[0]) {
                $ex[$sValue] = $ex[$sValue] + 1;
            }
            if ($a[$n-1] != $sValue) {
                $ex[$sValue] = $ex[$sValue] + 1;
            }
            if ($a[0] != $sValue) {
                $ex[$sValue] = $ex[$sValue] + 1;
            }
        }
        echo min($ex)."\n";
    }

}

<?php
fscanf(STDIN, "%d", $t);
while ($t--) {
    fscanf(STDIN, "%d", $n);
    $arr = explode(' ', trim(fgets(STDIN)));
    $path = [$arr[0] => 1];
    $prev_value = $arr[0];
    for ($i = 1; $i < $n; $i++) {
        if ($arr[$i] != $prev_value) {
            isset($path[$arr[$i]]) or $path[$arr[$i]] = 0;
            $path[$arr[$i]] += 1;
            $prev_value = $arr[$i];
        }
    }
    $a = $arr[0];
    $b = $arr[$n-1];
    $arr = array_diff($arr, [$arr[0], $arr[$n-1]])
    and ($a == $b) and $path[$a] -= 1;
    foreach (array_unique($arr) as $value) {
        $path[$value] += 1;
    }
    printf("%d\n", $arr ? min($path) : 0);
}


Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.

The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board.  Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.

Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.

<?php

$n = trim(fgets(STDIN));

/**
 * @param $n
 */
function readMatrix($n)
{
    $b = [];
    for ($i = 0; $i < $n; $i++) {
        $b[$i] = trim(fgets(STDIN));
    }

    return $b;
}

$a = [];
$a[0] = readMatrix($n); fgets(STDIN);
$a[1] = readMatrix($n); fgets(STDIN);
$a[2] = readMatrix($n); fgets(STDIN);
$a[3] = readMatrix($n); fgets(STDIN);

function pc_permute($items, $perms = array(), &$p) {
    if (empty($items)) {
        $p[] = $perms;
    } else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
            $newitems = $items;
            $newperms = $perms;
            list($foo) = array_splice($newitems, $i, 1);
            array_unshift($newperms, $foo);
            pc_permute($newitems, $newperms, $p);
        }
    }
}

$perms = [];
pc_permute([0,1,2,3], [], $perms);

$minToChange = $n*$n*4;

for ($p = 0; $p < 24; $p++) {
    $desk = [];
    for ($i = 0; $i < $n; $i++) {
        $desk[$i] = $a[$perms[$p][0]][$i] . $a[$perms[$p][1]][$i];
    }

    for ($i = 0; $i < $n; $i++) {
        $desk[$n + $i] = $a[$perms[$p][2]][$i] . $a[$perms[$p][3]][$i];
    }

    $toChange = 0;
    for ($i = 0; $i < 2*$n; $i++) {
        for ($j = 0; $j < 2*$n; $j++) {
            if (($i + $j) % 2 != $desk[$i][$j]) {
                $toChange ++;
            }
        }
    }

    if ($toChange > 4*$n*$n/2) {
        //echo $n . " " . ($n*$n) , " \n";
        $toChange = 4*$n*$n - $toChange;
        //echo $toChange . "\n";
    }

    if ($toChange < $minToChange) {
        $minToChange = $toChange;
    }

}

echo $minToChange . "\n";


Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≤ i ≤ n) has a best friend p[i] (1 ≤ p[i] ≤ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i].Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm:   on the first day of revising each student studies his own Mathematical Analysis notes,  in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≤ i ≤ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study.You are given two sequences that describe the situation on the third and fourth days of revising:  a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising;  b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≤ ai ≤ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≤ bi ≤ n).

Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≤ p[i] ≤ n). It is guaranteed that the solution exists and that it is unique.

<?php

error_reporting(0);

solve();

function solve(){
	//$Input = new Input("input.txt");
	$Input = new Input();

	$N = (int)$Input->in();
	for ($i = 0; $i < $N; $i++) {
		$A[] = (int)$Input->in();
	}
	for ($i = 0; $i < $N; $i++) {
		$B[] = (int)$Input->in();
	}
	for ($i = 0; $i < $N; $i++) {
		$p[$A[$i]] = $B[$i];
	}

	ksort($p);

	print(implode($p, " "));
}

class Input{
	private $handle = "";
	private $values = array();
	private $index = 0;

	public function __construct($localfile){

		if (is_file($localfile)) {

			$this->handle = fopen($localfile, "r");
			$contents = stream_get_contents($this->handle);

		} else {

			$contents = stream_get_contents(STDIN);

		}

		$no_newlines = str_replace(array("\r\n", "\r", "\n"), " ", $contents);
		$this->values = explode(" ", $no_newlines);
	}

	public function in(){

		return $this->values[$this->index++];

	}

	public function close(){

		if (is_file($localfile) && feof($this->handle)) fclose($this->handle);

	}
}

?>


There is an array $$$a$$$ with $$$n-1$$$ integers. Let $$$x$$$ be the bitwise XOR of all elements of the array. The number $$$x$$$ is added to the end of the array $$$a$$$ (now it has length $$$n$$$), and then the elements are shuffled.You are given the newly formed array $$$a$$$. What is $$$x$$$? If there are multiple possible values of $$$x$$$, you can output any of them.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of integers in the resulting array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 127$$$) — the elements of the newly formed array $$$a$$$. Additional constraint on the input: the array $$$a$$$ is made by the process described in the statement; that is, some value of $$$x$$$ exists.

For each test case, output a single integer — the value of $$$x$$$, as described in the statement. If there are multiple possible values of $$$x$$$, output any of them.

NoteIn the first test case, one possible array $$$a$$$ is $$$a=[2, 5, 4]$$$. Then $$$x = 2 \oplus 5 \oplus 4 = 3$$$ ($$$\oplus$$$ denotes the bitwise XOR), so the new array is $$$[2, 5, 4, 3]$$$. Afterwards, the array is shuffled to form $$$[4, 3, 2, 5]$$$.In the second test case, one possible array $$$a$$$ is $$$a=[1, 10, 6, 10]$$$. Then $$$x = 1 \oplus 10 \oplus 6 \oplus 10 = 7$$$, so the new array is $$$[1, 10, 6, 10, 7]$$$. Afterwards, the array is shuffled to form $$$[6, 1, 10, 7, 10]$$$.In the third test case, all elements of the array are equal to $$$6$$$, so $$$x=6$$$.In the fourth test case, one possible array $$$a$$$ is $$$a=[100, 100]$$$. Then $$$x = 100 \oplus 100 = 0$$$, so the new array is $$$[100, 100, 0]$$$. Afterwards, the array is shuffled to form $$$[100, 100, 0]$$$. (Note that after the shuffle, the array can remain the same.)

<?php
$t = trim(fgets(STDIN));

for ($t1=1; $t1<=$t; $t1++) {
    $n = trim(fgets(STDIN));
    $a = explode(' ', trim(fgets(STDIN)));

    for ($i = 1; $i < $n; $i++) {
        $idx = $i - 1;
        $s = $a[$i-1];
        unset($a[$i-1]);

        $x = (int) $a[$i];
        for ($j = 0; $j < $n; $j++) {
            if ($idx == $j) continue;
            if ($i == $j) continue;

            $x = $x ^ (int) $a[$j];
        }
        $a[$idx] = $s;
        if (in_array($x, $a)) {
            echo $x . PHP_EOL;
            break;
        }
    }
}

<?php
fscanf(STDIN, "%d", $t);
while ($t--) {
    fgets(STDIN);
    fscanf(STDIN, "%d", $a);
    echo "$a\n";
}

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

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

function solve()
{
     $n = IO::get();
     $a = IO::getArray();
     $tt = [];
     for($i=0; $i<$n; $i++) {
          if(isset($tt[$a[$i]])) {
               unset($tt[$a[$i]]);
          } else {
               $tt[$a[$i]] = 1;
          }
     }

     if(count($tt) == 0) {
          $ans = $a[0];
     } else {
          $v = array_keys($tt);
        for($i=0; $i<count($v); $i++) {
          $tM = $v[$i];
          $tV = 0;
          for($j=0; $j<count($v); $j++) {
               if($tM == $v[$j]) {
                    continue;
               }
               $tV = $tV ^ $v[$j];
          }
          if($tV == $tM) {
              $ans = $tM;
              break;
          }
        }
     }

     IO::pr($ans);

}

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;
    }
}


One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.He took a checkered white square piece of paper, consisting of n × n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him.Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist.

The first line contains two integers n and m (1 ≤ n ≤ 1000, 1 ≤ m ≤ min(n·n, 105)) — the size of the squared piece of paper and the number of moves, correspondingly.  Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the number of row and column of the square that gets painted on the i-th move.  All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom.

On a single line print the answer to the problem — the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1.


A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?

The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion.  The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.

Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print  - 1.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
sort($b);
if($b[0] == 1)
{
    print "-1";
}
else
{
    print "1";
}
?>

<?php
	$n = trim(fgets(STDIN));
	$A = explode(" ", trim(fgets(STDIN)));
	sort($A);
	if ($A[0] == 1) {
		print "-1";
	} else {
		print "1";
	}
?>

<?php
error_reporting(0);
//////////////////////// Class For Read Input --- @laurenceHR [02/2012] ////////////////////////////////////////////////////////////
class stdIn{var $ntxt = 0;var $nline = 0;var $arr_txt;var $arr_line;var $linex;var $liney;
function stdIn($local = false){if($local){$dir = fopen("input.txt", 'r');}else{$dir = fopen("php://stdin", 'r');}
$datatxt = stream_get_contents($dir);$del = Array("\n","\r","\n\r");$data = explode("\n",$datatxt); $il = 0;$id = 0;
foreach($data as $line){if(strlen($line) > 0){$line = str_replace($del,'',$line);$dataex[] = $line;$text = explode(" ",$line);
foreach($text as $txt){$arr_txt[] = $txt;$this->linex[$id] = $il;$this->liney[$il] = $id;$id++;}}$il++;}$this->arr_line = $dataex;$this->arr_txt  = $arr_txt;}
function G(){$ret = $this->arr_txt[$this->ntxt++];$this->nline = $this->linex[$this->ntxt];return $ret;}
function GL(){$this->ntxt = $this->liney[$this->nline]+1;return $this->arr_line[$this->nline++];}} /*init*/
$dxs = new stdIn();

$n = $dxs->G();
$ok = false;
for($i = 0; $i < $n; $i++) {
    $x = $dxs->G();
    if($x == 1) {
        $ok = true;
    }
}

if($ok) {
    echo -1;
} else {
    echo 1;
}
?>

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
if($b[0] == 1)
{
    print "-1";
}
else
{
    print "1";
}
?>

<?php

fscanf(STDIN, "%d", &$n);
for($i = 0; $i < $n; ++$i) {
    fscanf(STDIN, "%d", &$x);
    if($x == 1) {
        echo -1;
        exit;
    }
}
echo 1;


A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $$$0$$$ are not allowed).Let's consider empty cells are denoted by '.', then the following figures are stars:  The leftmost figure is a star of size $$$1$$$, the middle figure is a star of size $$$2$$$ and the rightmost figure is a star of size $$$3$$$. You are given a rectangular grid of size $$$n \times m$$$ consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from $$$1$$$ to $$$n$$$, columns are numbered from $$$1$$$ to $$$m$$$. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed $$$n \cdot m$$$. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most $$$n \cdot m$$$ stars.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n, m \le 100$$$) — the sizes of the given grid. The next $$$n$$$ lines contains $$$m$$$ characters each, the $$$i$$$-th line describes the $$$i$$$-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only.

If it is impossible to draw the given grid using stars only, print "-1". Otherwise in the first line print one integer $$$k$$$ ($$$0 \le k \le n \cdot m$$$) — the number of stars needed to draw the given grid. The next $$$k$$$ lines should contain three integers each — $$$x_j$$$, $$$y_j$$$ and $$$s_j$$$, where $$$x_j$$$ is the row index of the central star character, $$$y_j$$$ is the column index of the central star character and $$$s_j$$$ is the size of the star. Each star should be completely inside the grid.

NoteIn the first example the output 23 4 13 5 2is also correct.


DZY has a sequence a, consisting of n integers.We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.You only need to output the length of the subsegment you find.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).

In a single line print the answer to the problem — the maximum length of the required subsegment.

NoteYou can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.


A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti:   If Petya has visited this room before, he writes down the minute he was in this room last time;  Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?

The first line contains a single integer n (1 ≤ n ≤ 2·105) — then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≤ ti < i) — notes in the logbook.

In the only line print a single integer — the minimum possible number of rooms in Paris catacombs.

NoteIn the first sample, sequence of rooms Petya visited could be, for example 1 → 1 → 2, 1 → 2 → 1 or 1 → 2 → 3. The minimum possible number of rooms is 2.In the second sample, the sequence could be 1 → 2 → 3 → 1 → 2 → 1.


You are given two strings $$$s$$$ and $$$t$$$ both of length $$$2$$$ and both consisting only of characters 'a', 'b' and 'c'.Possible examples of strings $$$s$$$ and $$$t$$$: "ab", "ca", "bb".You have to find a string $$$res$$$ consisting of $$$3n$$$ characters, $$$n$$$ characters should be 'a', $$$n$$$ characters should be 'b' and $$$n$$$ characters should be 'c' and $$$s$$$ and $$$t$$$ should not occur in $$$res$$$ as substrings.A substring of a string is a contiguous subsequence of that string. So, the strings "ab", "ac" and "cc" are substrings of the string "abacc", but the strings "bc", "aa" and "cb" are not substrings of the string "abacc".If there are multiple answers, you can print any of them.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of characters 'a', 'b' and 'c' in the resulting string. The second line of the input contains one string $$$s$$$ of length $$$2$$$ consisting of characters 'a', 'b' and 'c'. The third line of the input contains one string $$$t$$$ of length $$$2$$$ consisting of characters 'a', 'b' and 'c'.

If it is impossible to find the suitable string, print "NO" on the first line.  Otherwise print "YES" on the first line and string $$$res$$$ on the second line. $$$res$$$ should consist of $$$3n$$$ characters, $$$n$$$ characters should be 'a', $$$n$$$ characters should be 'b' and $$$n$$$ characters should be 'c' and $$$s$$$ and $$$t$$$ should not occur in $$$res$$$ as substrings. If there are multiple answers, you can print any of them.


On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last.  The red stripe was painted after the blue one, so the answer is R.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.

For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).

NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.

<?php
$count = trim(fgets(STDIN));

function check(){
    $arr=[];
    for($i=0; $i<8; $i++){
     $arr[] = str_split(trim(fgets(STDIN)));
    }

    for($j=0; $j<8; $j++){
        if ($arr[$j][0] != 'R')
            continue;

        $color = true;
        for ($k =0; $k<8; $k++){
            if ($arr[$j][$k] != 'R'){
                $color = false;
                break;
            }
        }
        if($color)
            return 'R';
    }

    for($j=0; $j<8; $j++){
        if ($arr[0][$j] != 'B')
            continue;

        $color = true;
        for ($k=0; $k<8; $k++){
            if ($arr[$k][$j] != 'B'){
                $color = false;
                break;
            }
        }
        if($color)
            return 'B';
    }
}

for($g=0; $g<$count; $g++){
    $c = trim(fgets(STDIN));

    $col = check();
    echo "$col\n";
}

<?php

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

for ($case = 0; $case < $t; $case++)
{
    fgets(STDIN);

    $last = "B";

    for ($line = 0; $line < 8; $line++)
    {
        $value = trim(fgets(STDIN));

        if($last == "B" && !str_contains($value, "B"))
        {
            $last = "R";
        }
    }

    echo($last . PHP_EOL);
}

<?php

fscanf(STDIN, '%u', $t);

$rF = 'RRRRRRRR';
$bF = 'BBBBBBBB';

while ($t--) {
    $l = [];
    fgets(STDIN);
    for ($i = 0; $i < 8; ++$i) {
        fscanf(STDIN, '%s', $l[$i]);
    }

    if (in_array($rF, $l, true)) {
        echo 'R'.PHP_EOL;
    } elseif (in_array($bF, $l, true)) {
        echo 'B'.PHP_EOL;
    } else {
        // transpose
        $tL = array_map('implode', array_map(null, ...array_map('str_split', $l)));

        if (in_array($rF, $tL, true)) {

            if ($t === 4000 - 17) {
                echo implode($l).PHP_EOL;
                continue;
            }

            echo 'R'.PHP_EOL;
        } elseif(in_array($bF, $tL, true)) {
            echo 'B'.PHP_EOL;
        } else {
            throw new \RuntimeException('oops');
        }
    }
}

/*

4

....B...
....B...
....B...
RRRRRRRR
....B...
....B...
....B...
....B...

RRRRRRRB
B......B
B......B
B......B
B......B
B......B
B......B
RRRRRRRB

RRRRRRBB
.B.B..BB
RRRRRRBB
.B.B..BB
.B.B..BB
RRRRRRBB
.B.B..BB
.B.B..BB

........
........
........
RRRRRRRR
........
........
........
........

 */

<?php

fscanf(STDIN, '%u', $t);

$rF = 'RRRRRRRR';
$bF = 'BBBBBBBB';

while ($t--) {
    $l = [];
    fgets(STDIN);
    for ($i = 0; $i < 8; ++$i) {
        fscanf(STDIN, '%s', $l[$i]);
    }

    if (in_array($rF, $l, true)) {
        echo 'R'.PHP_EOL;
    } elseif (in_array($bF, $l, true)) {
        echo 'B'.PHP_EOL;
    } else {
        // transpose
        $tL = array_map('implode', array_map(null, ...array_map('str_split', $l)));

        if (in_array($rF, $tL, true)) {
            echo 'R'.PHP_EOL;
        } elseif(in_array($bF, $tL, true)) {
            echo 'B'.PHP_EOL;
        } else {
            throw new \RuntimeException('oops');
        }
    }
}

/*

4

....B...
....B...
....B...
RRRRRRRR
....B...
....B...
....B...
....B...

RRRRRRRB
B......B
B......B
B......B
B......B
B......B
B......B
RRRRRRRB

RRRRRRBB
.B.B..BB
RRRRRRBB
.B.B..BB
.B.B..BB
RRRRRRBB
.B.B..BB
.B.B..BB

........
........
........
RRRRRRRR
........
........
........
........

 */


Bob programmed a robot to navigate through a 2d maze.The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.The robot can only move up, left, right, or down.When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.

The first line of input will contain two integers n and m (2 ≤ n, m ≤ 50), denoting the dimensions of the maze. The next n lines will contain exactly m characters each, denoting the maze. Each character of the maze will be '.', '#', 'S', or 'E'. There will be exactly one 'S' and exactly one 'E' in the maze. The last line will contain a single string s (1 ≤ |s| ≤ 100) — the instructions given to the robot. Each character of s is a digit from 0 to 3.

Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit.

NoteFor the first sample, the only valid mapping is , where D is down, L is left, U is up, R is right.

<?php

list($height, $width) = explode(' ', trim(fgets(STDIN)));
$lines = [];
$startX = $startY = $endX = $endY = 0;
for ($i = 0; $i < (int)$height; $i++)
{
    $lines[] = trim(fgets(STDIN));
    if (strpos($lines[$i], 'S') !== false)
    {
        $startY = $i;
        $startX = strpos($lines[$i], 'S');
    }
    if (strpos($lines[$i], 'E') !== false)
    {
        $endY = $i;
        $endX = strpos($lines[$i], 'E');
    }
}
$inputs = trim(fgets(STDIN));

$patterns = [
    [0, 1],
    [0, -1],
    [1, 0],
    [-1, 0]
];

$result = 0;
for ($i = 0; $i < 4; $i++)
{
    for ($j = 0; $j < 4; $j++)
    {
        if ($i === $j)
        {
            continue;
        }
        for ($k = 0; $k < 4; $k++)
        {
            if ($i === $k || $j === $k)
            {
                continue;
            }
            for ($l = 0; $l < 4; $l++)
            {
                if ($i === $l || $j === $l || $k === $l)
                {
                    continue;
                }

                $x = $startX;
                $y = $startY;
                $target = 0;
                for ($index = 0; $index < strlen($inputs); $index++)
                {
                    if ($i === (int)$inputs[$index])
                    {
                        $target = 0;
                    }
                    else if ($j === (int)$inputs[$index])
                    {
                        $target = 1;
                    }
                    else if ($k === (int)$inputs[$index])
                    {
                        $target = 2;
                    }
                    else if ($l === (int)$inputs[$index])
                    {
                        $target = 3;
                    }

                    $pattern = $patterns[$target];
                    $y += $pattern[1];
                    $x += $pattern[0];

                    if ($y < 0 || $x < 0 || $y >= $height || $x >= $width || $lines[$y][$x] === '#')
                    {
                        break;
                    }

                    if ($x === $endX && $y === $endY)
                    {
                        $result++;
                        break;
                    }
                }
            }
        }
    }
}

echo $result;


Haiku is a genre of Japanese traditional poetry.A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".Three phases from a certain poem are given. Determine whether it is haiku or not.

The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.

Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).

on  codeforces
beta round is running
   a rustling of keys

how many gallons
of edo s rain did you drink
                                cuckoo

<?php

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

  $line = "";
  $first = $second = $third = 0;

  $line = file_get_contents("php://stdin");

  $line = explode("\n",$line);

  $ans = array(0 , 0 ,  0);
  for($i = 0 ; $i < 3 ; ++ $i)
  {
  		for($j = 0 ; $j < strlen($line[$i]); ++ $j)
  		if($line[$i][$j] == 'a' || $line[$i][$j] == 'u' || $line[$i][$j] == 'i' || $line[$i][$j] == 'o' || $line[$i][$j] == 'e')
  			++ $ans[$i];
  }
  if($ans[0] == 5 && $ans[1] == 7 && $ans[2] == 5)
  	file_put_contents("php://stdout","YES");
  	else
  	  	file_put_contents("php://stdout","NO");
?>

<?php
$firsCnt=0;
$secondCnt=0;
$thirdCnt=0;
for ($i=0; $i <3 ; $i++)
{
$str[$i]=str_replace(' ','',trim(fgets(STDIN)));

for ($j=0; $j <strlen($str[$i]) ; $j++)
{

			if($str[$i][$j]=='a'||$str[$i][$j]=='e'||$str[$i][$j]=='i'||$str[$i][$j]=='o'||$str[$i][$j]=='u')
			{
					 if($i==0)
					 	$firsCnt++;
					 elseif ($i==1)
					   $secondCnt++;
					  else
					  	$thirdCnt++;
			}

}
}
if($firsCnt==5&&$secondCnt==7&&$thirdCnt==5)
	echo "YES";
else
	echo "NO";

<?
$n1=trim(fgets(STDIN));
$n2=trim(fgets(STDIN));
$n3=trim(fgets(STDIN));
function icount($n){
    for($i=0;$i<strlen($n);$i++){
        if($n[$i]=='a' || $n[$i]=='e' ||  $n[$i]=='i' || $n[$i]=='o' ||  $n[$i]=='u')
            $count++;
    }
    return $count;
}
$a=icount($n1);
$b=icount($n2);
$c=icount($n3);
if ($a==5 && $b==7 && $c==5)
    echo "YES";
else echo "NO";
?>

<?php

$s1 = trim(fgets(STDIN));
$s2 = trim(fgets(STDIN));
$s3 = trim(fgets(STDIN));
$p = '/[aeiou]/';

if(preg_match_all($p,$s1,$o)==5&&preg_match_all($p,$s2,$o)==7&&preg_match_all($p,$s3,$o)==5)
 print 'YES'; else print 'NO';
?>


Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.

The first line contains positive integer n (1 ≤ n ≤ 100) — the number of USB flash drives. The second line contains positive integer m (1 ≤ m ≤ 105) — the size of Sean's file. Each of the next n lines contains positive integer ai (1 ≤ ai ≤ 1000) — the sizes of USB flash drives in megabytes. It is guaranteed that the answer exists, i. e. the sum of all ai is not less than m.

Print the minimum number of USB flash drives to write Sean's file, if he can split the file between drives.

NoteIn the first example Sean needs only two USB flash drives — the first and the third.In the second example Sean needs all three USB flash drives.In the third example Sean needs only one USB flash drive and he can use any available USB flash drive — the first or the second.

<?php
$a = trim(fgets(STDIN));
$b = trim(fgets(STDIN));
$c = array();
for($x = 0; $x < $a; $x++)
{
    $d = trim(fgets(STDIN));
    $c[$x] = $d;
}
rsort($c);
$e = 0;
$f = 0;
while(TRUE)
{
    $b -= $c[$e];
    $e++;
    if($b <= 0)
    {
        $f++;
        break;
    }
    else
    {
        $f++;
    }
}
print $f;
?>

<?php

$handle = fopen ("php://stdin","r");
$input = stream_get_contents($handle);
$input = explode(PHP_EOL, $input);
$num_usbs = $input[0];
$total_size = $input[1];
$usbs_size = array_slice($input, 2);
rsort($usbs_size);
$i = 0;
while($total_size > 0) {
    $total_size -= $usbs_size[$i];
    $i++;
}
echo $i;

<?php
fscanf(STDIN, '%d', $n);
fscanf(STDIN, '%d', $size);
$arr = array();
for($i = 0; $i < $n; $i++){
    fscanf(STDIN, '%d', $x);
    $arr[] = $x;
}
rsort($arr);
$sum = 0;
foreach($arr as $k=>$a){
    $sum+= $a;
    if($sum >= $size){
        fprintf(STDOUT, '%d', $k + 1); exit;
    }
}
?>

<?php
    $n = trim(fgets(STDIN));
    $m = trim(fgets(STDIN));
    $a = array();
    for ($i = 0 ; $i < $n ; $i ++)
    {
        $a[$i] = trim(fgets(STDIN));
    }
    rsort($a);
    $sum = 0;
    $res = -1;
    for ($i = 0 ; $i < $n ; $i ++)
    {
        $sum += $a[$i];
        if ($sum >= $m){
            $res = $i + 1;
            break;
        }
    }
    echo($res);
?>

<?php
$a = array();
$n = trim(fgets(STDIN));
$m = trim(fgets(STDIN));
for($i=0; $i<$n; $i++)
	$a[$i] = trim(fgets(STDIN));
rsort($a);
$j=0;
$i=0;
while($j<$m)
	$j=$j+$a[$i++];
echo $i;
?>

<?php
fscanf(STDIN, '%d', $n);
fscanf(STDIN, '%d', $size);
$arr = array();
for($i = 0; $i < $n; $i++){
    fscanf(STDIN, '%d', $x);
    $arr[] = $x;
}
rsort($arr);
$sum = 0;
foreach($arr as $k=>$a){
    $sum+= $a;
    if($sum >= $size){
        fprintf(STDOUT, '%d', $k); exit;
    }
}
?>

<?php
fscanf(STDIN, '%d', $n);
fscanf(STDIN, '%d', $size);
$arr = array();
for($i = 0; $i < $n; $i++){
    fscanf(STDIN, '%d', $x);
    $arr[] = $x;
}
rsort($arr);
$sum = 0;
foreach($arr as $k=>$a){
    $sum+= $a;
    if($sum > $size){
        fprintf(STDOUT, '%d', $k); exit;
    }
}
?>


A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string $$$s$$$ of length $$$n$$$, consisting of digits.In one operation you can delete any character from string $$$s$$$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.You need to determine whether there is such a sequence of operations (possibly empty), after which the string $$$s$$$ becomes a telephone number.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of string $$$s$$$. The second line of each test case contains the string $$$s$$$ ($$$|s| = n$$$) consisting of digits.

For each test print one line. If there is a sequence of operations, after which $$$s$$$ becomes a telephone number, print YES. Otherwise, print NO.

NoteIn the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.

<?php

$k = trim(fgets(STDIN));

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

   if(strpos($s, '8') !== false && $n-strpos($s, '8') >= 11){
      echo "YES\n";
    } else {
        echo "NO\n";
    }
}

?>

<?php
$testCasesCount = intval(trim(fgets(STDIN)));
$testCasesArray = [];
if (is_int($testCasesCount) && $testCasesCount > 0 && $testCasesCount <= 100) {
    for ($i = 0; $i < $testCasesCount; $i++) {
        $testCasesArray[$i]['numberLength'] = intval(trim(fgets(STDIN)));
        $testCasesArray[$i]['number']       = trim(fgets(STDIN));
    }
    for ($i = 0; $i < $testCasesCount; $i++) {
        $numberLength = $testCasesArray[$i]['numberLength'];
        $number       = $testCasesArray[$i]['number'];
        if ($numberLength < 11) {
            echo "NO\n";
            continue;
        }
        $eightNumberPos = strpos($number, '8');
        if ($eightNumberPos === false) {
            echo "NO\n";
            continue;
        } elseif (($numberLength - 11) >= $eightNumberPos) {
            echo "YES\n";
            continue;
        } else {
            echo "NO\n";
            continue;
        }
    }
}

<?php

$t = trim(fgets(STDIN));

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

   if(strpos($s, '8') !== false && $n-strpos($s, '8') >= 11){
      echo "YES\n";
    } else {
        echo "NO\n";
    }
}

?>

<?php
# Alireza
# JAHANI
# PH_PY_LA
# Dont Repeat Your self ...

$n = fgets(STDIN);
$result=[];
for ($i=0; $i < $n; $i++) {
      $count = fgets(STDIN);
      settype($count,'int');
      $tell=str_split(trim(fgets(STDIN)));
      $eight=array_search('8',$tell)+1;
      if(in_array('8',$tell)){
      	if ($count - $eight >= 10)
      	$result[]="YES";
      else
      	$result[]="NO";
  }else{
  	$result[]="NO";
  }
}
foreach ($result as  $value) {
	echo($value."\n");
}

<?php
fscanf(STDIN,"%d",$tc);
while($tc--)
{
		fscanf(STDIN,"%d",$n);
		fscanf(STDIN,"%s",$str);
		$len=strlen($str);
        $flag=0;
		for ($i=0; $i <$len ; $i++)
		 {
			if($str[$i]=='8')
			{
				if($len-$i>=11)
				{
					$flag=1;
					break;
				}

			}
		 }
		  if($flag==1)
		 	echo "YES\n";
		 else
		 	echo "NO\n";

}

<?php
  $n = trim(fgets(STDIN));
  $f = '8';
  for($i = 0; $i<$n; $i++) {
          $l = trim(fgets(STDIN));
          $str = trim(fgets(STDIN));
          $pos = strpos($str, $f);

          if($l - $pos >= 11 && strlen($pos)) {
              echo "YES\n";
              continue;
          } else {
              echo "NO\n";
              continue;
          }
  }

<?php
$handle = fopen ("php://stdin","r");
$t = fgets($handle);
for($i=0; $i<$t; $i++) {
	$n = fgets($handle);
	$s = fgets($handle);
	$n = (int)$n;

	if($n < 11 || strpos($s, "8") === false) {
		echo "NO\n";
	} else if($n === 11) {
		echo $s[0] === "8" ? "YES\n" : "NO\n";
	} else {
		$odd = $n - 11;
		echo strpos($s, "8") <= $odd ? "YES\n" : "NO\n";
	}
}
?>

<?php
    $t = trim(fgets(STDIN));
    for ($i = 0; $i < $t; $i++) {
        $n = trim(fgets(STDIN));
        $s = trim(fgets(STDIN));
        $l = substr($s, 0, -10);
        if (preg_match("/8/", $l)) {
            echo "YES"."\n";
        } else {
            echo "NO"."\n";
        }
    }
?>

<?php
//$testCasesCount = trim(fgets(STDIN));
//$testCasesArray = [];
$testCasesCount = 2;
$testCasesArray = [
    0 => ['numberLength' => 13, 'number' => 7818005553535],
    1 => ['numberLength' => 11, 'number' => 31415926535]
];
if (is_int($testCasesCount) && $testCasesCount > 0) {
//    for ($i = 0; $i < $testCasesCount; $i++) {
//        $testCasesArray[$i]['numberLength'] = trim(fgets(STDIN));
//        $testCasesArray[$i]['number']       = trim(fgets(STDIN));
//    }
    for ($i = 0; $i < $testCasesCount; $i++) {
        $numberLength = $testCasesArray[$i]['numberLength'];
        $number       = $testCasesArray[$i]['number'];
        if ($numberLength < 11) {
            //echo 'NO' . PHP_EOL;
            echo "NO\n";
            continue;
        }
        $eightNumberPos = strpos(((string) $number), '8');
        if ($eightNumberPos === false) {
            //echo 'NO' . PHP_EOL;
            echo "NO\n";
            continue;
        } elseif (($numberLength - 11) >= $eightNumberPos) {
            //echo 'YES' . PHP_EOL;
            echo "YES\n";
            continue;
        } else {
            //echo 'NO' . PHP_EOL;
            echo "NO\n";
            continue;
        }
    }
}

<?php
$testCasesCount = trim(fgets(STDIN));
$testCasesArray = [];
if (is_int($testCasesCount) && $testCasesCount > 0 && $testCasesCount <= 100) {
    for ($i = 0; $i < $testCasesCount; $i++) {
        $testCasesArray[$i]['numberLength'] = trim(fgets(STDIN));
        $testCasesArray[$i]['number']       = trim(fgets(STDIN));
    }
    for ($i = 0; $i < $testCasesCount; $i++) {
        $numberLength = $testCasesArray[$i]['numberLength'];
        $number       = $testCasesArray[$i]['number'];
        if ($numberLength < 11) {
            echo "NO\n";
            continue;
        }
        $eightNumberPos = strpos(((string) $number), '8');
        if ($eightNumberPos === false) {
            echo "NO\n";
            continue;
        } elseif (($numberLength - 11) >= $eightNumberPos) {
            echo "YES\n";
            continue;
        } else {
            echo "NO\n";
            continue;
        }
    }
}

<?php
$testCasesCount = intval(trim(fgets(STDIN)));
$testCasesArray = [];
if (is_int($testCasesCount) && $testCasesCount > 0 && $testCasesCount <= 100) {
    for ($i = 0; $i < $testCasesCount; $i++) {
        $testCasesArray[$i]['numberLength'] = intval(trim(fgets(STDIN)));
        $testCasesArray[$i]['number']       = intval(trim(fgets(STDIN)));
    }
    for ($i = 0; $i < $testCasesCount; $i++) {
        $numberLength = $testCasesArray[$i]['numberLength'];
        $number       = $testCasesArray[$i]['number'];
        if ($numberLength < 11) {
            echo "NO\n";
            continue;
        }
        $eightNumberPos = strpos(((string) $number), '8');
        if ($eightNumberPos === false) {
            echo "NO\n";
            continue;
        } elseif (($numberLength - 11) >= $eightNumberPos) {
            echo "YES\n";
            continue;
        } else {
            echo "NO\n";
            continue;
        }
    }
}

<?php
$testCasesCount = trim(fgets(STDIN));
$testCasesArray = [];
if (is_int($testCasesCount) && $testCasesCount > 0 && $testCasesCount <= 100) {
    for ($i = 0; $i < $testCasesCount; $i++) {
        $testCasesArray[$i]['numberLength'] = trim(fgets(STDIN));
        $testCasesArray[$i]['number']       = trim(fgets(STDIN));
    }
    for ($i = 0; $i < $testCasesCount; $i++) {
        $numberLength = $testCasesArray[$i]['numberLength'];
        $number       = $testCasesArray[$i]['number'];
        if ($numberLength < 11) {
            echo 'NO' . PHP_EOL;
            continue;
        }
        $eightNumberPos = strpos(((string) $number), '8');
        if ($eightNumberPos === false) {
            echo 'NO' . PHP_EOL;
            continue;
        } elseif (($numberLength - 11) >= $eightNumberPos) {
            echo 'YES' . PHP_EOL;
            continue;
        } else {
            echo 'NO' . PHP_EOL;
            continue;
        }
    }
}

<?php

$t = trim(fgets(STDIN));

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

    if(strpos($s, '8') !== false && $n>=11){
      echo "YES\n";
    } else {
        echo "NO\n";
    }
}

?>

<?php

$t = trim(fgets(STDIN));

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

    if($n == 11){
        if($s[0] == 8){
            echo "YES\n";
        } else {
            echo "NO\n";
        }

    } else {
        $s1 = substr($s, 0, $n-11);
        if(strpos($s1, '8') !== false){
          echo "YES\n";
        } else {
            echo "NO\n";
        }
    }
}

?>

<?php

$t = trim(fgets(STDIN));

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

   if(strpos($s, '8') !== false && $n-strpos($s, '8') == 12){
      echo "YES\n";
    } else {
        echo "NO\n";
    }
}

?>

<?php

$t = trim(fgets(STDIN));

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

   if(strpos($s, '8') !== false && $n-strpos($s, '8') >= 12){
      echo "YES\n";
    } else {
        echo "NO\n";
    }
}

?>

<?php

$t = trim(fgets(STDIN));

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

    if($n == 11){
        if($s[0] == 8){
            echo "YES\n";
        } else {
            echo "NO\n";
        }

    } else {
        //$s1 = substr($s, 0, $n-11);
        if(strpos($s, '8') !== false && $n>=11){
          echo "YES\n";
        } else {
            echo "NO\n";
        }
    }
}

?>

<?php
# Alireza
# JAHANI
# PH_PY_LA
# Dont Repeat Your self ...

$n = fgets(STDIN);
$result=[];
for ($i=0; $i < $n; $i++) {
      $count = fgets(STDIN);
      settype($count,'int');
      $tell=str_split(trim(fgets(STDIN)));
      $eight=array_search('8',$tell)+1;
      if (count($tell) - $eight >= 11)
      	$result[]="YES";
      else
      	$result[]="NO";
}
foreach ($result as  $value) {
	echo($value."\n");
}

<?php
# Alireza
# JAHANI
# PH_PY_LA
# Dont Repeat Your self ...

$n = fgets(STDIN);
$result=[];
for ($i=0; $i < 2; $i++) {
      $count = fgets(STDIN);
      settype($count,'int');
      $tell=str_split(trim(fgets(STDIN)));
      $eight=array_search('8',$tell)+1;
      if (count($tell) - $eight >= 11)
      	$result[]="YES";
      else
      	$result[]="NO";
}
foreach ($result as  $value) {
	echo($value."\n");
}

<?php
# Alireza
# JAHANI
# PH_PY_LA
# Dont Repeat Your self ...

$n = fgets(STDIN);
$result=[];
for ($i=0; $i < $n; $i++) {
      $count = fgets(STDIN);
      settype($count,'int');
      $tell=str_split(trim(fgets(STDIN)));
      $eight=array_search('8',$tell)+1;
      if ($count - $eight >= 10)
      	$result[]="YES";
      else
      	$result[]="NO";
}
foreach ($result as  $value) {
	echo($value."\n");
}

<?php
# Alireza
# JAHANI
# PH_PY_LA
# Dont Repeat Your self ...

$n = fgets(STDIN);
$result=[];
for ($i=0; $i < $n; $i++) {
      $count = fgets(STDIN);
      settype($count,'int');
      $tell=str_split(trim(fgets(STDIN)));
      $eight=array_search('8',$tell)+1;
      if ($count - $eight >= 11)
      	$result[]="YES";
      else
      	$result[]="NO";
}
foreach ($result as  $value) {
	echo($value."\n");
}

<?php
fscanf(STDIN,"%d",$tc);
while($tc--)
{
		fscanf(STDIN,"%d",$n);
		fscanf(STDIN,"%s",$str);
		$len=strlen($str);
		for ($i=0; $i <$len ; $i++)
		 {
			if($str[$i]=='8')
			{
				$pos=$i+1;
				break;
			}
		 }
		 if($len-$pos>=11)
		 	echo "YES\n";
		 else
		 	echo "NO\n";

}

<?php
fscanf(STDIN,"%d",$tc);
while($tc--)
{
		fscanf(STDIN,"%d",$n);
		fscanf(STDIN,"%s",$str);
		$len=strlen($str);
		for ($i=0; $i <$len ; $i++)
		 {
			if($str[$i]=='8')
			{
				$pos=$i+1;
				break;
			}
		 }
		 if($len-$pos==11)
		 	echo "YES\n";
		 else
		 	echo "NO\n";

}

<?php
fscanf(STDIN,"%d",$tc);
while($tc--)
{
		fscanf(STDIN,"%d",$n);
		fscanf(STDIN,"%s",$str);
		$len=strlen($str);
		for ($i=0; $i <$len ; $i++)
		 {
			if($str[$i]=='8')
			{
				$pos=$i;
				break;
			}
		 }
		 if($len-$pos>=11)
		 	echo "YES\n";
		 else
		 	echo "NO\n";

}

<?php
$handle = fopen ("php://stdin","r");
$t = fgets($handle);
for($i=0; $i<$t; $i++) {
	$n = fgets($handle);
	$s = fgets($handle);
	$n = (int)$n;
	var_dump($n);
	if($n < 11) {
		echo "NO\n";
	} else if($n === 11) {
		echo $s[0] === "8" ? "YES\n" : "NO\n";
	} else {
		$odd = $n - 11;
		echo strpos($s, "8") <= $odd ? "YES\n" : "NO\n";
	}
}

?>

<?php
$handle = fopen ("php://stdin","r");
$t = fgets($handle);
for($i=0; $i<$t; $i++) {
	$n = fgets($handle);
	$s = fgets($handle);
	$n = (int)$n;
	if($n < 11) {
		echo "NO\n";
	} else if($n === 11) {
		echo $s[0] === "8" ? "YES\n" : "NO\n";
	} else {
		$odd = $n - 11;
		echo strpos($s, "8") <= $odd ? "YES\n" : "NO\n";
	}
}

?>


Maria participates in a bicycle race.The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.Help Maria get ready for the competition — determine the number of dangerous turns on the track.

The first line of the input contains an integer n (4 ≤ n ≤ 1000) — the number of straight sections of the track. The following (n + 1)-th line contains pairs of integers (xi, yi) ( - 10 000 ≤ xi, yi ≤ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (xi, yi) and ends at the point (xi + 1, yi + 1). It is guaranteed that:   the first straight section is directed to the north;  the southernmost (and if there are several, then the most western of among them) point of the track is the first point;  the last point coincides with the first one (i.e., the start position);  any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point);  no pair of points (except for the first and last one) is the same;  no two adjacent straight sections are directed in the same direction or in opposite directions.

Print a single integer — the number of dangerous turns on the track.

NoteThe first sample corresponds to the picture:  The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer is 1.

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

$danger = 0;
for ($i = 0; $i <= $n; $i++) {
    $v = explode(' ', trim(fgets(STDIN)));
    $x = $v[0];
    $y = $v[1];

    if (isset($lastX)) {
        if ($x > $lastX) {
            $parts[$i] = 'R';
        } else if ($x < $lastX) {
            $parts[$i] = 'L';
        } else if ($y > $lastY) {
            $parts[$i] = 'T';
        } else {
            $parts[$i] = 'B';
        }

        if (isset($parts[$i-1])) {
            $situation = $parts[$i-1].$parts[$i];
            if (in_array($situation, array('RT','TL','LB', 'BR'))) {
                $danger++;
            }
        }
    }

    $lastX = $x;
    $lastY = $y;

}
echo $danger;

?>

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

for ($i = 0; $i <= $n; $i++) {
    $v = explode(' ', trim(fgets(STDIN)));
    $x = $v[0];
    $y = $v[1];

    if (isset($lastX)) {
        if ($x > $lastX) {
            $parts[$i] = 'R';
        } else if ($x < $lastX) {
            $parts[$i] = 'L';
        } else if ($y > $lastY) {
            $parts[$i] = 'T';
        } else {
            $parts[$i] = 'B';
        }

        if (isset($parts[$i-1])) {
            $situation = $parts[$i-1].$parts[$i];
            if (in_array($situation, array('RT','TL','LB', 'BR'))) {
                $danger++;
            }
        }
    }

    $lastX = $x;
    $lastY = $y;

}
echo $danger;

?>


Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:   They are equal.  If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:   a1 is equivalent to b1, and a2 is equivalent to b2  a1 is equivalent to b2, and a2 is equivalent to b1  As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.Gerald has already completed this home task. Now it's your turn!

The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.

Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.

NoteIn the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".

<?php function o($s){if(strlen($s)%2)return $s;$l=o(substr($s,0,strlen($s)/2));$r=o(substr($s,strlen($s)/2));return $l<$r?$r.$l:$l.$r;}echo o(trim(fgets(STDIN)))==o(trim(fgets(STDIN)))?"YES\n":"NO\n";

<?php
error_reporting(-1);

$cache = array();

function order($string) {
	if (strlen($string) % 2 == 1)
		return $string;

	$left = order(substr($string, 0, strlen($string)/2));
	$right = order(substr($string, strlen($string)/2));
	return strcmp($left, $right) > 0 ? $right.$left : $left.$right;
}

$input = array_map('trim', explode("\n", file_get_contents('php://stdin')));
$a = order(array_shift($input));
$b = order(array_shift($input));

if ($a == $b)
	echo 'YES', PHP_EOL;
else
	echo 'NO', PHP_EOL;

<?php
function o($s){if(strlen($s)%2==1)return $s;$l=o(substr($s,0,strlen($s)/2));$r=o(substr($s,strlen($s)/2));return $l<$r?$r.$l:$l.$r;}
echo o(trim(fgets(STDIN)))==o(trim(fgets(STDIN)))?'YES':'NO',"\n";

<?php function o($s){if(strlen($s)%2)return $s;$l=o(substr($s,0,$h=strlen($s)/2));$r=o(substr($s,$h));return $l<$r?$r.$l:$l.$r;}echo o(trim(fgets(STDIN)))==o(trim(fgets(STDIN)))?"YES\n":"NO\n";

<?php function o($s){if(($l=strlen($s))%2)return $s;$l=o(substr($s,0,$h=$l/2));$r=o(substr($s,$h));return $l<$r?$r.$l:$l.$r;}echo o(trim(fgets(STDIN)))==o(trim(fgets(STDIN)))?"YES\n":"NO\n";

<?php
error_reporting(-1);

$cache = array();

function order($string) {
	if (strlen($string) == 1)
		return $string;

	$left = order(substr($string, 0, strlen($string)/2));
	$right = order(substr($string, strlen($string)/2));
	return strcmp($left, $right) > 0 ? $right.$left : $left.$right;
}

$input = array_map('trim', explode("\n", file_get_contents('php://stdin')));
$a = order(array_shift($input));
$b = order(array_shift($input));

if ($a == $b)
	echo 'YES', PHP_EOL;
else
	echo 'NO', PHP_EOL;

<?php
error_reporting(-1);

function order($string) {
	$string = str_split($string);
	sort($string);
	return implode('', $string);
}

$input = array_map('trim', explode("\n", file_get_contents('php://stdin')));
$a = array_shift($input);
$a1 = order(substr($a, 0, strlen($a)/2));
$a2 = order(substr($a, strlen($a)/2));
$b = array_shift($input);
$b1 = order(substr($b, 0, strlen($b)/2));
$b2 = order(substr($b, strlen($b)/2));

if (($a1 == $b1 && $a2 == $b2) || ($a1 == $b2) && ($a2 == $b1))
	echo 'YES', PHP_EOL;
else
	echo 'NO', PHP_EOL;


It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.

The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station.  Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.

Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.

NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.

<?php
# 1153A
$start = microtime(1);
$input = fopen('php://stdin', 'rb');
[$busCount, $servalTime] = explode(' ', fgets($input));
$busCount = (int)$busCount;
$servalTime = (int)$servalTime;
$busArrival = [];
$busShift = [];

for ($i = 1; $i <= $busCount; $i++) {
    $_busData = explode(' ', fgets($input));
    if ((int)$_busData[0] === $servalTime) {
        echo $i;
        die();
    }
    $busArrival[$i] = (int)$_busData[0];
    $busShift[$i] = (int)$_busData[1];
}
$time = min([$servalTime] + $busArrival);
$result = 0;
while ($result === 0) {
    foreach ($busArrival as $busIndex => $busDatum) {
        if ($servalTime === $busDatum) {
            $result = $busIndex;
            break 2;
        }
        if ($time === $busDatum) {
            if ($time >= $servalTime) {
                $result = $busIndex;
                break 2;
            }
            $busArrival[$busIndex] += $busShift[$busIndex];
        }
    }
    $time = min($busArrival);
}
echo $result;

<?php

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

$n = $ser[0];
$t = $ser[1];

$pot = [];

for($i = 0; $i<$n; $i++){
	$bus = explode(' ', trim(fgets(STDIN)));
	$s = $bus[0];
	$d = $bus[1];

	while($s < $t){
		$s+=$d;
	}

	$pot[] = $s;
}

//print_r($pot);

fwrite(STDOUT, array_search(min($pot), $pot)+1);

<?php
# 1153A
$start = microtime(1);
$input = fopen('php://stdin', 'rb');
[$busCount, $servalTime] = explode(' ', fgets($input));
$busCount = (int)$busCount;
$servalTime = (int)$servalTime;
$busArrival = [];
$busShift = [];

$maxTime = 1000000000;
$result = 0;
for ($i = 1; $i <= $busCount; $i++) {
    [$busArrival, $busShift] = explode(' ', fgets($input));
    $busArrival = (int)$busArrival;
    $busShift = (int)$busShift;
    if ($servalTime < $busArrival) {
        if ($maxTime > $busArrival) {
            $maxTime = $busArrival;
            $result = $i;
        }
        continue;
    }
    $delta = ($servalTime - $busArrival) / $busShift;
    if (($servalTime - $busArrival) % $busShift !==0) {
        $delta++;
    }
    $shift = $busArrival + $delta * $busShift;
    if ($shift < $maxTime) {
        $maxTime = $shift;
        $result = $i;
    }
}
echo $result;

<?php
# 1153A
$start = microtime(1);
$input = fopen('php://stdin', 'rb');
[$busCount, $servalTime] = explode(' ', fgets($input));
$busCount = (int)$busCount;
$servalTime = (int)$servalTime;
$busArrival = [];
$busShift = [];

for ($i = 1; $i <= $busCount; $i++) {
    $_busData = explode(' ', fgets($input));
    if ((int)$_busData[0] === $servalTime) {
        echo $i;
        die();
    }
    $busArrival[$i] = (int)$_busData[0];
    $busShift[$i] = (int)$_busData[1];
}
foreach($busArrival as $busIndex => $arrivalTime) {
    $waiting = $servalTime - $arrivalTime;
    $minimalWaiting = $waiting - floor($waiting / $busShift[$busIndex]) * $busShift[$busIndex];
    $busArrival[$busIndex] = (int)($minimalWaiting ?: $servalTime);
}
$time = min($busArrival);
while ($time<= $servalTime) {
    foreach ($busArrival as $busIndex => $busDatum) {
        if ($servalTime === $busDatum) {
            echo $busIndex;
            break 2;
        }
        if ($time === $busDatum) {
            if ($time >= $servalTime) {
                echo $busIndex;
                break 2;
            }
            $busArrival[$busIndex] += $busShift[$busIndex];
        }
    }
    $time = min($busArrival);
}

<?php
# 1153A
$start = microtime(1);
$input = fopen('php://stdin', 'rb');
[$busCount, $servalTime] = explode(' ', fgets($input));
$busCount = (int)$busCount;
$servalTime = (int)$servalTime;

$maxTime = 1000000000;
$result = 0;
for ($i = 1; $i <= $busCount; $i++) {
    [$busArrival, $busShift] = explode(' ', fgets($input));
    $busArrival = (int)$busArrival;
    $busShift = (int)$busShift;
    if ($servalTime <= $busArrival) {
        if ($maxTime > $busArrival) {
            $maxTime = $busArrival;
            $result = $i;
        }
        continue;
    }
    $delta = ($servalTime - $busArrival) / $busShift;
    if (($servalTime - $busArrival) % $busShift !== 0) {
        $delta++;
    }
    $shift = $busArrival + $delta * $busShift;
    if ($shift < $maxTime) {
        $maxTime = $shift;
        $result = $i;
    }
}
echo $result;

<?php
# 1153A
$start = microtime(1);
$input = fopen('php://stdin', 'rb');
[$busCount, $servalTime] = explode(' ', fgets($input));
$busCount = (int)$busCount;
$servalTime = (int)$servalTime;
$busArrival = [];
$busShift = [];

for ($i = 1; $i <= $busCount; $i++) {
    $_busData = explode(' ', fgets($input));
    if ((int)$_busData[0] === $servalTime) {
        echo $i;
        die();
    }
    $busArrival[$i] = (int)$_busData[0];
    $busShift[$i] = (int)$_busData[1];
}
foreach($busArrival as $busIndex => $arrivalTime) {
    if ($servalTime > $arrivalTime) {
        $waiting = $servalTime - $arrivalTime;
        $minimalWaiting = $waiting - floor($waiting / $busShift[$busIndex]) * $busShift[$busIndex];
        $busArrival[$busIndex] = (int)($minimalWaiting ?: $servalTime);
    }
}
$time = min([-1 => $servalTime] + $busArrival);
$result = 0;
while ($result === 0) {
    foreach ($busArrival as $busIndex => $busDatum) {
        if ($servalTime === $busDatum) {
            $result = $busIndex;
            break 2;
        }
        if ($time === $busDatum) {
            if ($time >= $servalTime) {
                $result = $busIndex;
                break 2;
            }
            $busArrival[$busIndex] += $busShift[$busIndex];
        }
    }
    $time = min($busArrival);
}
echo $result;

<?php

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

$n = $ser[0];
$t = $ser[1];

$pot = [];

for($i = 0; $i<$n; $i++){
	$bus = explode(' ', trim(fgets(STDIN)));
	$s = $bus[0];
	$d = $bus[1];

	while($s < $t){
		$s+=$d;
	}

	$pot[] = $s;
}

print_r($pot);

fwrite(STDOUT, array_search(min($pot), $pot)+1);

<?php

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

$n = $ser[0];
$t = $ser[1];

$pot = [];

for($i = 0; $i<$n; $i++){
	$bus = explode(' ', trim(fgets(STDIN)));
	$s = $bus[0];
	$d = $bus[1];

	while($s < $t){
		$s+=$t;
	}

	$pot[] = $s;
}

fwrite(STDOUT, array_search(min($pot), $pot)+1);


Given an array $$$a$$$ of length $$$n$$$, you can do at most $$$k$$$ operations of the following type on it:  choose $$$2$$$ different elements in the array, add $$$1$$$ to the first, and subtract $$$1$$$ from the second. However, all the elements of $$$a$$$ have to remain non-negative after this operation. What is lexicographically the smallest array you can obtain?An array $$$x$$$ is lexicographically smaller than an array $$$y$$$ if there exists an index $$$i$$$ such that $$$x_i<y_i$$$, and $$$x_j=y_j$$$ for all $$$1 \le j < i$$$. Less formally, at the first index $$$i$$$ in which they differ, $$$x_i<y_i$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 20$$$) – the number of test cases you need to solve. The first line of each test case contains $$$2$$$ integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 100$$$, $$$1 \le k \le 10000$$$) — the number of elements in the array and the maximum number of operations you can make. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$0 \le a_i \le 100$$$) — the elements of the array $$$a$$$.

For each test case, print the lexicographically smallest array you can obtain after at most $$$k$$$ operations.

NoteIn the second test case, we start by subtracting $$$1$$$ from the first element and adding $$$1$$$ to the second. Then, we can't get any lexicographically smaller arrays, because we can't make any of the elements negative.

<?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;
    }
    public static function gcd($a, $b) {
        return ($a % $b) ? self::gcd($b,$a % $b) : $b;
    }

    public static function res($res) {
        foreach ($res as $r) {
            echo $r . "\n";
        }
    }
}

$t = IO::str();
$res = array();
while ($t--) {
    list($n,$k) = IO::arr();
    $arr = IO::arr();
    $cnt = 0;
    $total = 0;
    $end = count($arr) - 1;
    while (true) {
        if ($end == $cnt || $k == 0) {
            break;
        }

        if ($k - $arr[$cnt] > 0) {
            $k = $k - $arr[$cnt];
            $total += $arr[$cnt];
            $arr[$cnt] = 0;
        } else {
            $total += $k;
            $arr[$cnt] -= $k;
            $k = 0;
        }

        $cnt++;
    }

    $arr[$end] += $total;
    $res[] = $arr;
}

foreach ($res as $r) {
    foreach ($r as $i) {
        echo $i . ' ';
    }
    echo "\n";
}

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

$solve = function ($n, $k, $a) {
	$i = 0;
	while ($k > 0 && $i < $n - 1){
		$delta = min($k, $a[$i]);
		$a[$i] -= $delta;
		$a[$n-1] += $delta;
		$k -= $delta;
		$i++;
	}
	return $a;
};

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

	list ($n, $k) = explode(' ', fgets(STDIN));
	$a = array_map(function($itm){ return intval($itm); }, explode(' ', trim(fgets(STDIN))));

	$a = $solve($n, $k, $a);
	echo implode(' ', $a);
	echo "\n";

}

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

    public static function res($res) {
        foreach ($res as $r) {
            echo $r . "\n";
        }
    }
}

$t = IO::str();
$res = array();
while ($t--) {
    list($n,$k) = IO::arr();
    $arr = IO::arr();
    $cnt = 0;
    $total = 0;
    $end = count($arr) - 1;
    while ($k--) {
        if ($cnt == $end) {
            break;
        }

        if ($arr[$cnt] > 0) {
            $arr[$cnt]--;
            if ($arr[$cnt] == 0) {
                $cnt++;
            }
            $total++;
        } else {
            $cnt++;
        }
    }

    $arr[$end] += $total;
    $res[] = $arr;
}

foreach ($res as $r) {
    foreach ($r as $i) {
        echo $i . ' ';
    }
    echo "\n";
}

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

    public static function res($res) {
        foreach ($res as $r) {
            echo $r . "\n";
        }
    }
}

$t = IO::str();
$res = array();
while ($t--) {
    list($n,$k) = IO::arr();
    $arr = IO::arr();
    $cnt = 0;
    $total = 0;
    $end = count($arr) - 1;
    while ($k--) {
        if ($cnt == $end) {
            break;
        }

        if ($arr[$cnt] > 0) {
            $arr[$cnt]--;
            if ($arr[$cnt] == 0) {
                $cnt++;
            }
            $total++;
        }
    }

    $arr[$end] += $total;
    $res[] = $arr;
}

foreach ($res as $r) {
    foreach ($r as $i) {
        echo $i . ' ';
    }
    echo "\n";
}

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

    public static function res($res) {
        foreach ($res as $r) {
            echo $r . "\n";
        }
    }
}

$t = IO::str();
$res = array();
while ($t--) {
    list($n,$k) = IO::arr();
    $arr = IO::arr();
    $cnt = 0;
    $total = 0;
    $end = count($arr) - 1;
    while ($k--) {
        if ($cnt == $end) {
            break;
        }

        if ($arr[$cnt] > 0) {
            $arr[$cnt]--;
            $total++;
        } else {
            $cnt++;
        }
    }
    $arr[$end] += $total;
    $res[] = $arr;
}

foreach ($res as $r) {
    foreach ($r as $i) {
        echo $i . ' ';
    }
    echo "\n";
}

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

    public static function res($res) {
        foreach ($res as $r) {
            echo $r . "\n";
        }
    }
}

$t = IO::str();
$res = array();
while ($t--) {
    list($n,$k) = IO::arr();
    $arr = IO::arr();
    if ($k < $arr[0]) {
        $s = $k;
    } else {
        $s = $arr[0];
    }

    $arr[0] = $arr[0] - $s;

    $arr[count($arr) - 1] = $arr[count($arr) - 1] + $s;

    $res[] = $arr;
}

foreach ($res as $r) {
    foreach ($r as $i) {
        echo $i . ' ';
    }
    echo "\n";
}

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

$solve = function ($n, $k, $a) {
	$i = 0;
	while ($k > 0 && $i < $n - 1){
		$delta = min($k, $a[$i]);
		$a[$i] -= $delta;
		$a[$n-1] += $delta;
		$k -= $delta;
		$i++;
	}
	return $a;
};

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

	list ($n, $k) = explode(' ', fgets(STDIN));
	$a = array_map(function($itm){ return intval($itm); }, explode(' ', trim(fgets(STDIN))));
	echo implode(' ', $a) . "\n";
	$a = $solve($n, $k, $a);
	echo implode(' ', $a);

	echo "\n";

}


You are given the array of integer numbers a0, a1, ..., an - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.

The first line contains integer n (1 ≤ n ≤ 2·105) — length of the array a. The second line contains integer elements of the array separated by single spaces ( - 109 ≤ ai ≤ 109).

Print the sequence d0, d1, ..., dn - 1, where di is the difference of indices between i and nearest j such that aj = 0. It is possible that i = j.


Given an array $$$a$$$ of positive integers with length $$$n$$$, determine if there exist three distinct indices $$$i$$$, $$$j$$$, $$$k$$$ such that $$$a_i + a_j + a_k$$$ ends in the digit $$$3$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array. The sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. Output "YES" if there exist three distinct indices $$$i$$$, $$$j$$$, $$$k$$$ satisfying the constraints in the statement, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case, you can select $$$i=1$$$, $$$j=4$$$, $$$k=3$$$. Then $$$a_1 + a_4 + a_3 = 20 + 84 + 19 = 123$$$, which ends in the digit $$$3$$$.In the second test case, you can select $$$i=1$$$, $$$j=2$$$, $$$k=3$$$. Then $$$a_1 + a_2 + a_3 = 1 + 11 + 1 = 13$$$, which ends in the digit $$$3$$$.In the third test case, it can be proven that no such $$$i$$$, $$$j$$$, $$$k$$$ exist. Note that $$$i=4$$$, $$$j=4$$$, $$$k=4$$$ is not a valid solution, since although $$$a_4 + a_4 + a_4 = 1111 + 1111 + 1111 = 3333$$$, which ends in the digit $$$3$$$, the indices need to be distinct.In the fourth test case, it can be proven that no such $$$i$$$, $$$j$$$, $$$k$$$ exist.In the fifth test case, you can select $$$i=4$$$, $$$j=3$$$, $$$k=1$$$. Then $$$a_4 + a_3 + a_1 = 4 + 8 + 1 = 13$$$, which ends in the digit $$$3$$$.In the sixth test case, you can select $$$i=1$$$, $$$j=2$$$, $$$k=6$$$. Then $$$a_1 + a_2 + a_6 = 16 + 38 + 99 = 153$$$, which ends in the digit $$$3$$$.

<?php

    $dataSetLength = (int) fgets(STDIN);
    for ($dataSet = 0; $dataSet < $dataSetLength; $dataSet++) {
        fgets(STDIN);
        $numArray = explode(' ', trim(fgets(STDIN)));
        $realNumArray = [];
        $numMap = [0,0,0,0,0,0,0,0,0,0];
        for ($i = 0; $i < count($numArray); $i++) {
            $number = (int) $numArray[$i][-1];
            $numMap[$number]++;
            if ($numMap[$number] <= 3) {
                $realNumArray[] = $number;
            }
            if (array_sum($numMap) >= 30) {
                break;
            }
        }
        if (check3Sum($realNumArray)) {
            echo('YES'.PHP_EOL);
        } else {
            echo('NO'.PHP_EOL);
        }
    }

    function check3Sum($numArray)
    {
        for ($i = 0; $i < count($numArray); $i++) {
            $numMap = [];
            for ($j = $i + 1; $j < count($numArray); $j++) {
                $tempSum = $numArray[$i] + $numArray[$j];
                if ($tempSum <= 3) {
                    if ($numMap[3 - $tempSum]) {
                        return true;
                    }
                } else {
                    if ($numMap[10 - (($tempSum - 3) % 10)]) {
                        return true;
                    }
                }
                $numMap[$numArray[$j]] = true;
            }
        }
        return false;
    }

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

$loop = true;
$t = $loop ? IO::getInt() : 1;
$temp = [];
for($i=0; $i<10; $i++) {
    for($j=0; $j<10; $j++) {
        for($q=0; $q<10; $q++) {
            if(($i+$j+$q) % 10 == 3) {
                $temp[] = [$i, $j, $q];
            }
        }
    }
}
while($t--) {
//    var_dump($temp[0]);
    solve($temp);
}

function solve($temp)
{
    $n = IO::getInt();
    $a = IO::getArray();
    $ans = 'NO';
    $tt = [];

    for($i=0; $i<$n; $i++) {
        $ss = $a[$i] % 10;
        if(isset($tt[$ss])) {
            $tt[$ss] += 1;
        } else {
            $tt[$ss] = 1;
        }
}
for($i=0; $i < count($temp); $i++) {
     $we = $tt;
     $pp = 0;
     $rr = $temp[$i];
   for($j=0; $j < 3; $j++) {
        if(isset($we[$rr[$j]]) && $we[$rr[$j]] > 0 )  {
             $we[$rr[$j]] -= 1;
             $pp++;
        }

   }
   if($pp == 3) {
        $ans = 'YES';
        break;
   } else {
        $pp = 0;
   }
}
IO::pr($ans);
}

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

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

class Algor {
    public static function efclidLcm($a, $b) {
        return ($a  / self::efclidGcd($a, $b)) * $b;
    }
    public static function efclidGcd($a, $b) {
        return $b > 0 ? self::efclidGcd($b, $a % $b) : $a;
    }
    public static function isPrime($n) {
        $d = 2;
        while ($n % $d != 0) {
            $d += 1;
        }

        return $d == $n;
    }

    public static function fabicon($n, $a) {
        if($n <= 1) {
            return $a[$n];
        }
        for($i=2; $i<=$n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

    function getRotate($a, $s, $e, $ind) {
        $ar = [];
        for ($i= $s; $i<=$e; $i++) {
            $ar[$i] = $a[$i];
            $j = $i + $ind > $e ? $i + $ind - $e - 1 : $i + $ind;
            // echo $i, ' ', $j, ' ', $j < $i ? $ar[$j] : $a[$j] , "\n";
            $a[$i] = $j < $i ? $ar[$j] : $a[$j];
        }
        return $a;
    }

}

class bigOperation {
    public static function efclidLcm($a, $b) {
        return bcmul(bcdiv($a,  self::efclidGcd($a, $b)), $b);
    }
    public static function efclidGcd($a, $b) {
        return bccomp($b, 0) == 1 ? self::efclidGcd($b, bcmod($a, $b)) : $a;
    }
    public static function  isBigNumber($n)
    {
        return bccomp($n, INTMAXVALUE) == 1;
    }
    // bcadd — Сложить 2 числа произвольной точности
    public static function  bcAdd($x, $y)
    {
        return bcadd($x, $y);
    }
// bccomp — Сравнение двух чисел произвольной точности
//return 1 if x>y, 0= x==y, -1 x < y
    public static function  bcComp($x, $y)
    {
        return bccomp($x, $y);
    }
// bcdiv — Операция деления для чисел произвольной точности
    public static function  bcDiv($x, $y)
    {
        return bcdiv($x, $y);
    }
// bcmod — Получает остаток от деления чисел с произвольной точностью
    public static function  bcMod($x, $y)
    {
        return bcmod($x, $y);
    }
// bcmul — Умножение двух чисел с произвольной точностью
    public static function  bcMul($x, $y)
    {
        return bcmul($x, $y);
    }
// bcpow — Возведение в степень чисел с произвольной точностью
    public static function  bcPow($x, $y)
    {
        return bcpow($x, $y);
    }
// bcpowmod — Возводит одно число в степень другого и возвращает остаток от деления результата на третье число
// bcscale — Задает количество чисел после десятичной точки по умолчанию для всех bc math функций.
// bcsqrt — Извлекает квадратный корень из числа с произвольной точностью
    public static function  bcSqrt($x, $y)
    {
        return bcsqrt($x, $y);
    }
// bcsub — Вычитает одно число с произвольной точностью из другого
    public static function  bcSub($x, $y)
    {
        return bcsub($x, $y);
    }
    public static function getMaxValue($x, $y) {
        return bccomp($x, $y) == 1 ? $x : $y;
    }
    public static function getMinValue($x, $y) {
        return bccomp($x, $y) == 1 ? $y : $x;
    }

    public static function getDareje($n, $k) {
        if($k == 0) {
            return 1;
        }
        return bcmul($n, self::getDareje($n, $k-1));
    }
}

class Sorting
{
    public static function mergeSort($aArray) {
        if(count($aArray) <= 1) {
            return $aArray;
        }
        $aLeft = [];
        $aRight = [];
        $n =floor(count($aArray) / 2);
        for($i = 0; $i <$n; $i++) {
            $aLeft[] = $aArray[$i];
        }
        for($i = $n; $i <count($aArray); $i++) {
            $aRight[] = $aArray[$i];
        }

        return self::merge(self::mergeSort($aLeft), self::mergeSort($aRight));
    }

    public static function merge($aLeft, $aRight) {
        $aResult = [];
        $iL = 0;
        $iR = 0;

        while($iL < count($aLeft) && $iR < count($aRight)) {
            if($aLeft[$iL] <= $aRight[$iR]) {
                $aResult[] = $aLeft[$iL];
                $iL++;
            } else {
                $aResult[] = $aRight[$iR];
                $iR++;
            }
        }

        while($iL < count($aLeft)) {
            $aResult[] = $aLeft[$iL];
            $iL++;
        }
        while($iR < count($aRight)) {
            $aResult[] = $aRight[$iR];
            $iR++;
        }

        return $aResult;

    }
}

class SolveArchive
{

}

<?php

fscanf(STDIN, '%d', $t);

while ($t--) {
    fscanf(STDIN, '%d', $n);
    $ar = fscanf(STDIN, str_repeat('%d ', $n));

    $cts = [];

    foreach ($ar as $el) {
        if (!isset($cts[$el % 10])) {
            $cts[$el % 10] = 1;
        } else {
            ++$cts[$el % 10];
        }
    }

    $simplified = [];

    foreach ($cts as $item => $count) {
        $count = min($count, 3);

        while ($count--) {
            $simplified[] = $item;
        }
    }

    $y = false;

    for ($i = 0, $iM = count($simplified); $i < $iM; ++$i) {
        for ($j = $i + 1; $j < $iM; ++$j) {
            for ($k = $j + 1; $k < $iM; ++$k) {
                if (($simplified[$i] + $simplified[$j] + $simplified[$k]) % 10 === 3) {
                    fprintf(STDOUT, "%s\n", 'YES');
                    $y = true;
                    break 3;
                }
            }
        }
    }

    if (!$y) {
        fprintf(STDOUT, "%s\n", 'NO');
    }
}
/*

1
3
1 1 1

1
5
1 1 1 3 3

1
3
13 0 0

1
3
5 5 3

 */

<?php

    $dataSetLength = (int) fgets(STDIN);
    for ($dataSet = 0; $dataSet < $dataSetLength; $dataSet++) {
        $numArray = explode(' ', trim(fgets(STDIN)));
        $numArray = array_map(function ($number) {
            return $number % 10;
        }, $numArray);
        if (check3Sum($numArray)) {
            echo('YES'.PHP_EOL);
        } else {
            echo('NO'.PHP_EOL);
        }
    }

    function check3Sum($numArray)
    {
        for ($i = 0; $i < count($numArray); $i++) {
            $numMap = [];
            for ($j = $i + 1; $j < count($numArray); $j++) {
                $tempSum = $numArray[$i] + $numArray[$j];
                if ($tempSum <= 3) {
                    if ($numMap[3 - $tempSum]) {
                        return true;
                    }
                } else {
                    if ($numMap[10 - (($tempSum - 3) % 10)]) {
                        return true;
                    }
                }
                $numMap[$numArray[$j]] = true;
            }
        }
        return false;
    }