This is an interactive problem!Ehab plays a game with Laggy. Ehab has 2 hidden integers $$$(a,b)$$$. Laggy can ask a pair of integers $$$(c,d)$$$ and Ehab will reply with:  1 if $$$a \oplus c>b \oplus d$$$.  0 if $$$a \oplus c=b \oplus d$$$.  -1 if $$$a \oplus c<b \oplus d$$$. Operation $$$a \oplus b$$$ is the bitwise-xor operation of two numbers $$$a$$$ and $$$b$$$.Laggy should guess $$$(a,b)$$$ with at most 62 questions. You'll play this game. You're Laggy and the interactor is Ehab.It's guaranteed that $$$0 \le a,b<2^{30}$$$.

To print the answer, print "! a b" (without quotes). Don't forget to flush the output after printing the answer.

NoteIn the sample:The hidden numbers are $$$a=3$$$ and $$$b=1$$$.In the first query: $$$3 \oplus 2 = 1$$$ and $$$1 \oplus 1 = 0$$$, so the answer is 1.In the second query: $$$3 \oplus 1 = 2$$$ and $$$1 \oplus 2 = 3$$$, so the answer is -1.In the third query: $$$3 \oplus 2 = 1$$$ and $$$1 \oplus 0 = 1$$$, so the answer is 0.Then, we printed the answer.

<?php

$n = 30;
$k = 2*$n + 2;
$checks = 0;
$checkMemo = [];

$a = 19;//random_int(0, (1<<$n)-1);
$b = 511;//random_int(0, (1<<$n)-1);

function check1($c, $d) {
	global $checks;
	global $a;
	global $b;
	global $checkMemo;

	if (isset($checkMemo["$c.$d"])) {
		return $checkMemo["$c.$d"];
	}

	$checks++;
	$res = ($a^$c)<=>($b^$d);
	$checkMemo["$c.$d"] = $res;
	return $checkMemo["$c.$d"];
}

function check($c, $d) {
	global $checkMemo;

	if (isset($checkMemo["$c.$d"])) {
		return $checkMemo["$c.$d"];
	}

	echo "? $c $d\n";
	flush();
	$res = intval(fgets(STDIN));

	$checkMemo["$c.$d"] = $res;
	return $checkMemo["$c.$d"];
}

$adda = $addb = 0;
$equals = [];
$i = $n-1;
while ($i>=0) {
	$res = check($adda, $addb);
	if ($res == 0) {
		$equals[] = $i;
	} else {
		$r = check($adda + (1<<$i), $addb + (1<<$i));
		if ($r!=$res) {
			if ($res>0) {
				$adda += 1<<$i;
			} else {
				$addb += 1<<$i;
			}
		} else {
			$equals[] = $i;
		}
	}

	$i--;
}

foreach ($equals as $i) {
	$res = check($adda + (1<<$i), $addb);
	if ($res<0) {
		$adda += 1<<$i;
		$addb += 1<<$i;
	}
}

echo "! $adda $addb\n";

<?php

$n = 4;
$k = 2*$n + 2;
$checks = 0;
$checkMemo = [];

$a = random_int(0, (1<<$n)-1);
$b = random_int(0, (1<<$n)-1);

function check2($c, $d) {
	global $checks;
	global $a;
	global $b;
	global $checkMemo;

	if (isset($checkMemo["$c.$d"])) {
		return $checkMemo["$c.$d"];
	}

	$checks++;
	$res = ($a^$c)<=>($b^$d);
	echo "check: $c, $d => $res\n";
	$checkMemo["$c.$d"] = $res;
	return $checkMemo["$c.$d"];
}

function check($c, $d) {
	global $checks;
	global $checkMemo;

	if (isset($checkMemo["$c.$d"])) {
		return $checkMemo["$c.$d"];
	}

	$checks++;
	echo "? $c $d\n";
	flush();
	$res = intval(fgets(STDIN));
	// echo "check: $c, $d => $res\n";
	$checkMemo["$c.$d"] = $res;
	return $checkMemo["$c.$d"];
}

$i = $n-1;
$adda = $addb = 0;
$equals = [];
while ($i>=0) {
	$res = check($adda, $addb);
	if ($res > 0) {
		$r = check($adda + (1<<$i), $addb + (1<<$i));
		if ($r!=$res) {
			//echo "a[$i]==1, b[$i]==0\n";
			$adda += 1<<$i;
		} else {
			//echo "a[$i]==b[$i]\n";
			$equals[] = $i;
		}
	} elseif ($res<0) {
		$r = check($adda + (1<<$i), $addb + (1<<$i));
		if ($r!=$res) {
			//echo "a[$i]==0, b[$i]==1\n";
			$addb += 1<<$i;
		} else {
			//echo "a[$i]==b[$i]\n";
			$equals[] = $i;
		}
	} else {
		//echo "a[$i]==b[$i]\n";
		$equals[] = $i;
	}

	$i--;
}

foreach ($equals as $i) {
	$res = check($adda + (1<<$i), $addb);
	if ($res<0) {
		$adda += 1<<$i;
		$addb += 1<<$i;
	}
}

// echo "a' = ".decbin($adda).", b' = ".decbin($addb)."\n";
// echo "a = ".decbin($a).", b = ".decbin($b)."\n\n";

// echo "checks: $checks ($k)\n";
// echo ($a==$adda && $b==$addb && $checks<=$k) ? "+\n" : "-\n";
echo "! $adda $addb\n";
//echo "! $a $b\n";
flush();


Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.

The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.

If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:   the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,  the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,  the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,  Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.

6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC


You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints.

For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists.

NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$.

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

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

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

        $x = intval($in_str[0]) ;
        $y = intval($in_str[1]) ;
        $n = intval($in_str[2]) ;

        $d = intval($n / $x) * $x ;

        if($d + $y <= $n) echo $d + $y . "\n" ;
        else echo $d - $x + $y . "\n" ;
    }
?>


You have one chip and one chance to play roulette. Are you feeling lucky?

Print your bet. Your chip must be placed entirely within some square (not on an edge or a corner shared by adjacent squares).


This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) > n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.

NoteIn the first example, the graph could look like this  The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$.   The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$.  With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$.  In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.

<?php

// 1729 E. Guess the Cycle Size
// _probability_, _interactive_

for ($i = 3; $i < 25 + 3; ++$i) {
    fprintf(STDOUT, '? %d %d'.PHP_EOL, 1, $i);
    fprintf(STDOUT, '? %d %d'.PHP_EOL, $i, 1);

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

    if ($first === -1) {
        fprintf(STDOUT, '! %d' . PHP_EOL, $i - 1);
        break;
    }

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

    if ($first !== $second) {
        fprintf(STDOUT, '! %d' . PHP_EOL, $first + $second);
        break;
    }
}

<?php

// 1729 E. Guess the Cycle Size
// _probability_, _interactive_

for ($i = 3; $i < 25 + 3; ++$i) {
    fprintf(STDOUT, '? %d %d'.PHP_EOL, 1, $i);
    fprintf(STDOUT, '? %d %d'.PHP_EOL, $i, 1);
//    fflush(STDOUT);

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

    if ($first === -1) {
        fprintf(STDOUT, '! %d' . PHP_EOL, $i - 1);
        break;
    }

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

    if ($first !== $second) {
        fprintf(STDOUT, '! %d' . PHP_EOL, $first + $second);
        break;
    }
}

<?php

for ($i = 3; $i < 25 + 3; ++$i) {
    fprintf(STDOUT, '? %d %d'.PHP_EOL, 1, $i);
    fprintf(STDOUT, '? %d %d'.PHP_EOL, $i, 1);
    fflush(STDOUT);

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

    if ($first === -1) {
        fprintf(STDOUT, '! %d' . PHP_EOL, $i - 1);
        break;
    }

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

    if ($first !== $second) {
        fprintf(STDOUT, '! %d' . PHP_EOL, $first + $second);
        break;
    }
}


3R2 - Standby for ActionOur dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. $$$n$$$"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are $$$s$$$ ($$$s > 0$$$) opponents remaining and $$$t$$$ ($$$0 \le t \le s$$$) of them make a mistake on it, JOE receives $$$\displaystyle\frac{t}{s}$$$ dollars, and consequently there will be $$$s - t$$$ opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?

The first and single line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$), denoting the number of JOE's opponents in the show.

Print a number denoting the maximum prize (in dollars) JOE could have. Your answer will be considered correct if it's absolute or relative error won't exceed $$$10^{-4}$$$. In other words, if your answer is $$$a$$$ and the jury answer is $$$b$$$, then it must hold that $$$\frac{|a - b|}{max(1, b)} \le 10^{-4}$$$.

NoteIn the second example, the best scenario would be: one contestant fails at the first question, the other fails at the next one. The total reward will be $$$\displaystyle \frac{1}{2} + \frac{1}{1} = 1.5$$$ dollars.

<?php

$n = intval(readline());

$joe = 0;
for ($i=1; $i<=$n; $i++) {
	$joe += 1/$i;
}

print $joe;

<?php
$i = trim(fgets(STDIN));
$count = 0;
for($j = $i; $j>0; $j--){
    $count += 1/$j;
}
echo $count;


You are given three strings $$$a$$$, $$$b$$$ and $$$c$$$ of the same length $$$n$$$. The strings consist of lowercase English letters only. The $$$i$$$-th letter of $$$a$$$ is $$$a_i$$$, the $$$i$$$-th letter of $$$b$$$ is $$$b_i$$$, the $$$i$$$-th letter of $$$c$$$ is $$$c_i$$$.For every $$$i$$$ ($$$1 \leq i \leq n$$$) you must swap (i.e. exchange) $$$c_i$$$ with either $$$a_i$$$ or $$$b_i$$$. So in total you'll perform exactly $$$n$$$ swap operations, each of them either $$$c_i \leftrightarrow a_i$$$ or $$$c_i \leftrightarrow b_i$$$ ($$$i$$$ iterates over all integers between $$$1$$$ and $$$n$$$, inclusive).For example, if $$$a$$$ is "code", $$$b$$$ is "true", and $$$c$$$ is "help", you can make $$$c$$$ equal to "crue" taking the $$$1$$$-st and the $$$4$$$-th letters from $$$a$$$ and the others from $$$b$$$. In this way $$$a$$$ becomes "hodp" and $$$b$$$ becomes "tele".Is it possible that after these swaps the string $$$a$$$ becomes exactly the same as the string $$$b$$$?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a string of lowercase English letters $$$a$$$. The second line of each test case contains a string of lowercase English letters $$$b$$$. The third line of each test case contains a string of lowercase English letters $$$c$$$. It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding $$$100$$$.

Print $$$t$$$ lines with answers for all test cases. For each test case: If it is possible to make string $$$a$$$ equal to string $$$b$$$ print "YES" (without quotes), otherwise print "NO" (without quotes). You can print either lowercase or uppercase letters in the answers.

4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim

NoteIn the first test case, it is impossible to do the swaps so that string $$$a$$$ becomes exactly the same as string $$$b$$$.In the second test case, you should swap $$$c_i$$$ with $$$a_i$$$ for all possible $$$i$$$. After the swaps $$$a$$$ becomes "bca", $$$b$$$ becomes "bca" and $$$c$$$ becomes "abc". Here the strings $$$a$$$ and $$$b$$$ are equal.In the third test case, you should swap $$$c_1$$$ with $$$a_1$$$, $$$c_2$$$ with $$$b_2$$$, $$$c_3$$$ with $$$b_3$$$ and $$$c_4$$$ with $$$a_4$$$. Then string $$$a$$$ becomes "baba", string $$$b$$$ becomes "baba" and string $$$c$$$ becomes "abab". Here the strings $$$a$$$ and $$$b$$$ are equal.In the fourth test case, it is impossible to do the swaps so that string $$$a$$$ becomes exactly the same as string $$$b$$$.

<?php
list($m) = explode(' ', trim(fgets(STDIN)));
for($k = 0; $k < $m; $k++) {
    $a = trim(fgets(STDIN));
    $b = trim(fgets(STDIN));
    $c = trim(fgets(STDIN));
    $bFlag = false;
    for ($i = 0; $i < strlen($a); $i++) {
        if ($c[$i] == $a[$i] || $c[$i] == $b[$i]) {
            $bFlag = true;
        } else {
            $bFlag = false;
            break;
        }
    }

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

}

<?php

function solution(string $a, string $b, string $c): bool
{
    $a = str_split($a);
    $b = str_split($b);
    $c = str_split($c);
    for ($i = 0; $i < count($a); $i++) {
        if ($a[$i] == $c[$i] || $b[$i] == $c[$i]) {
            continue;
        }
        return false;
    }
    return true;
}

$n = intval(fgets(STDIN));
for ($i = 0; $i < $n; $i++) {
    $a = trim(fgets(STDIN));
    $b = trim(fgets(STDIN));
    $c = trim(fgets(STDIN));
    print (solution($a, $b, $c) ? 'YES' : 'NO') . PHP_EOL;
}

<?php
fscanf(STDIN, "%d\n",$tc);
while ($tc--) {
	fscanf(STDIN,"%s\n",$frst);
	fscanf(STDIN,"%s\n",$second);
	fscanf(STDIN,"%s\n",$third);

	for($i=0;$i<strlen($third);$i++)
	{
		if($third[$i]!=$frst[$i])
		{
			$tmp=$third[$i];
			$third[$i]=$frst[$i];
			$frst[$i]=$tmp;
		}
		elseif ($third[$i]!=$second[$i]) {
			$tmp=$third[$i];
			$third[$i]=$second[$i];
			$second[$i]=$tmp;
		}

    }
if($frst==$second)
	echo "YES\n";
else
	echo "NO\n";
}

<?php
$i = trim(fgets(STDIN));
for($j = 0; $j < $i; $j++){
    $a = str_split(trim(fgets(STDIN)));
    $b = str_split(trim(fgets(STDIN)));
    $c = str_split(trim(fgets(STDIN)));
    $bool = true;
    foreach($c as $k => $v){
        if($v != $a[$k] && $v != $b[$k]){
            $bool = false;
        }
    }
    if($bool){
        echo "YES\n";
    } else {
        echo "NO\n";
    }

}

<?php
function solve($t)
{

}
$server = "php://stdin";
$handle = fopen($server, "r");
$t = trim(fgets($handle));
for ($j=0;$j<$t;$j++)
{
    $a= trim(fgets($handle));
    $b = trim(fgets($handle));
    $c = trim(fgets($handle));
    $count=0;
    for ($i=0;$i<strlen($a);$i++)
    {
        if($a[$i]==$c[$i] ||$b[$i]==$c[$i])
        {
            $count++;
        }
    }
    if($count==strlen($a))
    {
        echo "YES"."\n";
    }else
    {
        echo "NO"."\n";
    }
}

?>

<?php
list($m) = explode(' ', trim(fgets(STDIN)));
for($k = 0; $k < $m; $k++) {
    $a = trim(fgets(STDIN));
    $b = trim(fgets(STDIN));
    $c = trim(fgets(STDIN));
    $aTest = [];
    $bFlag = false;
    for ($i = 0; $i < strlen($a); $i++) {
        if ($c[$i] == $a[$i] || $c[$i] == $b[$i]) {
            $bFlag = true;
        } else {
            $bFlag = false;
        }
    }

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

}


Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.In total, Nastya dropped $$$n$$$ grains. Nastya read that each grain weighs some integer number of grams from $$$a - b$$$ to $$$a + b$$$, inclusive (numbers $$$a$$$ and $$$b$$$ are known), and the whole package of $$$n$$$ grains weighs from $$$c - d$$$ to $$$c + d$$$ grams, inclusive (numbers $$$c$$$ and $$$d$$$ are known). The weight of the package is the sum of the weights of all $$$n$$$ grains in it.Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the $$$i$$$-th grain weighs some integer number $$$x_i$$$ $$$(a - b \leq x_i \leq a + b)$$$, and in total they weigh from $$$c - d$$$ to $$$c + d$$$, inclusive ($$$c - d \leq \sum\limits_{i=1}^{n}{x_i} \leq c + d$$$).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$  — the number of test cases.  The next $$$t$$$ lines contain descriptions of the test cases, each line contains $$$5$$$ integers: $$$n$$$ $$$(1 \leq n \leq 1000)$$$  — the number of grains that Nastya counted and $$$a, b, c, d$$$ $$$(0 \leq b < a \leq 1000, 0 \leq d < c \leq 1000)$$$  — numbers that determine the possible weight of one grain of rice (from $$$a - b$$$ to $$$a + b$$$) and the possible total weight of the package (from $$$c - d$$$ to $$$c + d$$$).

For each test case given in the input print "Yes", if the information about the weights is not inconsistent, and print "No" if $$$n$$$ grains with masses from $$$a - b$$$ to $$$a + b$$$ cannot make a package with a total mass from $$$c - d$$$ to $$$c + d$$$.

NoteIn the first test case of the example, we can assume that each grain weighs $$$17$$$ grams, and a pack $$$119$$$ grams, then really Nastya could collect the whole pack.In the third test case of the example, we can assume that each grain weighs $$$16$$$ grams, and a pack $$$128$$$ grams, then really Nastya could collect the whole pack.In the fifth test case of the example, we can be assumed that $$$3$$$ grains of rice weigh $$$2$$$, $$$2$$$, and $$$3$$$ grams, and a pack is $$$7$$$ grams, then really Nastya could collect the whole pack.In the second and fourth test cases of the example, we can prove that it is impossible to determine the correct weight of all grains of rice and the weight of the pack so that the weight of the pack is equal to the total weight of all collected grains.

<?php

for($t = intval(trim(fgets(STDIN))); $t > 0; $t --){
    //print pow(2, intval(fgets(STDIN)) - 1)."\n";
    list($n, $a, $b, $c, $d) = explode(" ", trim(fgets(STDIN)));

    if($n * ($a - $b) > $c + $d || $n * ($a + $b) < $c - $d)
        print("NO\n");

    else
        print("YES\n");

}

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

    function solve($x, $y, $a, $b)
    {
    }

    $T = intval(fgets(STDIN));
    while($T --)
    {
        $Nastya = explode(" ", trim(fgets(STDIN))) ;

        $n = intval($Nastya[0]) ;
        $a = intval($Nastya[1]) ;
        $b = intval($Nastya[2]) ;
        $c = intval($Nastya[3]) ;
        $d = intval($Nastya[4]) ;

        $tmp_a = $n * ($a - $b) ;
        $tmp_b = $n * ($a + $b) ;
        $tmp_c = $c - $d ;
        $tmp_d = $c + $d ;

        if($tmp_a > $tmp_d) echo "NO" . "\n" ;
        else if($tmp_c > $tmp_b) echo "NO"."\n" ;
        else echo "YES"."\n" ;
    }
?>

<?php

for($t = intval(trim(fgets(STDIN))); $t > 0; $t --){
    //print pow(2, intval(fgets(STDIN)) - 1)."\n";
    list($n, $a, $b, $c, $d) = explode(" ", trim(fgets(STDIN)));
    $flag = 0;

    for($i = $a - $b; $i <= $a + $b; $i++){
        if($n * $i >= $c - $d && $n * $i <= $c + $d)
            $flag = 1;
    }

    if($flag)
        print("YES\n");

    else
        print("NO\n");

}

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

    $Nastya = array_fill(0, 5, 0) ;

    function solve($x, $y, $a, $b)
    {
    }

    $a = intval(fgets(STDIN));
    while($a --)
    {
        $Nastya = explode(" ", fgets(STDIN)) ;

        $n = intval($Nastya[0]) ;
        $a = intval($Nastya[1]) ;
        $b = intval($Nastya[2]) ;
        $c = intval($Nastya[3]) ;
        $d = intval($Nastya[4]) ;

        $tmp_a = $n * ($a - $b) ;
        $tmp_b = $n * ($a + $b) ;
        $tmp_c = $c - $d ;
        $tmp_d = $c + $d ;

        if($tmp_a > $tmp_d) echo "NO" . "\n" ;
        else if($tmp_c > $tmp_b) echo "NO"."\n" ;
        else echo "YES"."\n" ;
    }
?>


To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the selling are made only once. To carry out his plan, Qwerty is going to take a bank loan that covers all expenses and to return the loaned money at the end of the operation (the money is returned without the interest). At the same time, Querty wants to get as much profit as possible.The system has n planets in total. On each of them Qwerty can buy or sell items of m types (such as food, medicine, weapons, alcohol, and so on). For each planet i and each type of items j Qwerty knows the following: aij — the cost of buying an item;  bij — the cost of selling an item;  cij — the number of remaining items.It is not allowed to buy more than cij items of type j on planet i, but it is allowed to sell any number of items of any kind.Knowing that the hold of Qwerty's ship has room for no more than k items, determine the maximum profit which Qwerty can get.

The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 10, 1 ≤ m, k ≤ 100) — the number of planets, the number of question types and the capacity of Qwerty's ship hold, correspondingly. Then follow n blocks describing each planet. The first line of the i-th block has the planet's name as a string with length from 1 to 10 Latin letters. The first letter of the name is uppercase, the rest are lowercase. Then in the i-th block follow m lines, the j-th of them contains three integers aij, bij and cij (1 ≤ bij < aij ≤ 1000, 0 ≤ cij ≤ 100) — the numbers that describe money operations with the j-th item on the i-th planet. The numbers in the lines are separated by spaces. It is guaranteed that the names of all planets are different.

Print a single number — the maximum profit Qwerty can get.

NoteIn the first test case you should fly to planet Venus, take a loan on 74 units of money and buy three items of the first type and 7 items of the third type (3·6 + 7·8 = 74). Then the ranger should fly to planet Earth and sell there all the items he has bought. He gets 3·9 + 7·9 = 90 units of money for the items, he should give 74 of them for the loan. The resulting profit equals 16 units of money. We cannot get more profit in this case.


An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full.Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000"  →  "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address.Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below:  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::";  "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0";  "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0";  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000";  "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.You've got several short records of IPv6 addresses. Restore their full record.

The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.

For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.


Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.

The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.

Print "YES", if the dwarves belong to the same race. Otherwise, print "NO".

Note  First example: you can simply swap two letters in string "ab". So we get "ba".  Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b".

<?php
$str1=trim(fgets(STDIN));
$str2=trim(fgets(STDIN));
$len1=strlen($str1);
$len2=strlen($str2);
if($len1!=$len2)
{
echo "NO\n";
}
else{
$j=0;
$count=0;
$a=array();
$b=array();
for ($i=0; $i <$len1 ; $i++)
{
	if($str1[$i]!=$str2[$i])
	 {
     $a[$j]=$str1[$i];
     $b[$j]=$str2[$i];
     $j++;
      $count++;
      if($count>2)
      {
      	//$flag=1;
      	//echo "NO";
      	break;
      }
     }
}

if($count==2&&$a[1]==$b[0]&&$a[0]==$b[1])
	echo "YES\n";
else
	echo "NO";

}

<?php

fscanf(STDIN, "%s", $a);
fscanf(STDIN, "%s", $b);

$ra = preg_split("//", $a);
$rb = preg_split("//", $b);

sort($ra);
sort($rb);

$a = implode("", $ra);
$b = implode("", $rb);

die(($a == $b ? "YES" : "NO"));

?>

<?php
$str1=trim(fgets(STDIN));
$str2=trim(fgets(STDIN));
if(strlen($str1)!=strlen($str2))
echo "NO\n";
else{
$split1=str_split($str1);
$split2=str_split($str2);
sort($split1);
sort($split2);
$alphabet="abcdefghijklmnopqrstuvwxyz";
$str3="";
for ($i=0; $i <strlen($alphabet) ; $i++)
{     $cnt=0;
	for ($j=0; $j <count($split1) ; $j++)
	{
		if($alphabet[$i]==$split1[$j])
		{
		  $cnt++;
			//break;
		}
	}
	$str3.=$alphabet[$i].$cnt;
}
$str4="";
for ($i=0; $i <strlen($alphabet) ; $i++)
{     $cnt=0;
	for ($j=0; $j <count($split2) ; $j++)
	{
		if($alphabet[$i]==$split2[$j])
		{
		  $cnt++;
			//break;
		}
	}
	$str4.=$alphabet[$i].$cnt;
}
if($str3==$str4)
	echo "YES\n";

else
	echo "NO\n";
}


This is yet another problem dealing with regular bracket sequences.We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.

The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.

Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".

<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $string = fgets($stdin);

    $string = rtrim($string, "\n");
    $numb_such = 0;
    $cur_max_len = 0;
    $cur_len = 0;
    $open=0;
    for($i=0;$i<strlen($string);++$i){
        if($string[$i]=="(") $open++;
        else $open--;

        $cur_len++;

        if($open < 0){
            if(($cur_len-1)>$cur_max_len) {
                $cur_max_len = $cur_len-1;
                $numb_such=1;
            }
            else if(($cur_len-1) == $cur_max_len) $numb_such++;
            $cur_len = 0;
            $open=0;
        }
    }

    if($open>0){
     /*   for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $string[$i]=")";
            else if($string[$i]==")") $string[$i]="(";
        }
*/
        $string = strrev($string);

        $cur_len = 0;
        $open=0;
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]==")") {
                $open++;
                $cur_len++;
            }

            else if($string[$i]=="(") {
                $open--;
                $cur_len++;
            }

            if($open < 0){
                if(($cur_len-1)>$cur_max_len) {
                    $cur_max_len = $cur_len-1;
                    $numb_such=1;
                }
                else if(($cur_len-1) == $cur_max_len) $numb_such++;
                $cur_len = 0;
                $open=0;
            }
        }
    }

    if(($cur_max_len!=0)&&($numb_such==0)) $numb_such=1;
    if($cur_max_len==0) $numb_such=1;
    fputs($stdout, $cur_max_len . " " . $numb_such);

?>

<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $string = fgets($stdin);

    $string = rtrim($string, "\n");
    $numb_such = 0;
    $cur_max_len = 0;
    $cur_len = 0;
    $open=0;
    for($i=0;$i<strlen($string);++$i){
        if($string[$i]=="(") $open++;
        else $open--;

        $cur_len++;

        if($open < 0){
            if(($cur_len-1)>$cur_max_len) {
                $cur_max_len = $cur_len-1;
                $numb_such=1;
            }
            else if(($cur_len-1) == $cur_max_len) $numb_such++;
            $cur_len = 0;
            $open=0;
        }
    }

    if($open>0){
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $string[$i]=")";
            else $string[$i]="(";
        }

        $string = substr(strrev($string), 0, $cur_len-1);

        $cur_len = 0;
        $open=0;
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $open++;
            else $open--;

            $cur_len++;

            if($open < 0){
                if(($cur_len-1)>$cur_max_len) {
                    $cur_max_len = $cur_len-1;
                    $numb_such=1;
                }
                else if(($cur_len-1) == $cur_max_len) $numb_such++;
                $cur_len = 0;
                $open=0;
            }
        }
    }

    if(($cur_max_len!=0)&&($numb_such==0)) $numb_such=1;
    if($cur_max_len==0) $numb_such=1;
    fputs($stdout, $cur_max_len . " " . $numb_such);
?>

<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $string = fgets($stdin);

    $string = rtrim($string, " \r\n");

    $numb_such = 0;
    $cur_max_len = 0;
    $cur_len = 0;
    $open=0;

    for($i=0;$i<strlen($string);++$i){
        if($string[$i]=="(") $open++;
        else $open--;

        $cur_len++;

        if($open < 0){
            if(($cur_len-1)>$cur_max_len) {
                $cur_max_len = $cur_len-1;
                $numb_such=1;
            }
            else if(($cur_len-1) == $cur_max_len) $numb_such++;
            $cur_len = 0;
            $open=0;
        }
    }

    if($open>0){
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $string[$i]=")";
            else $string[$i]="(";
        }

        $string = substr(strrev($string), 0, $cur_len-1);

        $cur_len = 0;
        $open=0;
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $open++;
            else $open--;

            $cur_len++;

            if($open < 0){
                if(($cur_len-1)>$cur_max_len) {
                    $cur_max_len = $cur_len-1;
                    $numb_such=1;
                }
                else if(($cur_len-1) == $cur_max_len) $numb_such++;
                $cur_len = 0;
                $open=0;
            }
        }
    }

    if(($cur_max_len!=0)&&($numb_such==0)) $numb_such=1;
    if($cur_max_len==0) $numb_such=1;
    fputs($stdout, $cur_max_len . " " . $numb_such);
?>

<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $string = fgets($stdin);

    $numb_such = 0;
    $cur_max_len = 0;
    $cur_len = 0;
    $open=0;
    for($i=0;$i<strlen($string);++$i){
        if($string[$i]=="(") $open++;
        else $open--;

        $cur_len++;

        if($open < 0){
            if(($cur_len-1)>$cur_max_len) {
                $cur_max_len = $cur_len-1;
                $numb_such=1;
            }
            else if(($cur_len-1) == $cur_max_len) $numb_such++;
            $cur_len = 0;
            $open=0;
        }
    }

    if($open>0){
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $string[$i]=")";
            else $string[$i]="(";
        }

        $string = substr(strrev($string), 1, $cur_len);

        $cur_len = 0;
        $open=0;
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $open++;
            else $open--;

            $cur_len++;

            if($open < 0){
                if(($cur_len-1)>$cur_max_len) {
                    $cur_max_len = $cur_len-1;
                    $numb_such=1;
                }
                else if(($cur_len-1) == $cur_max_len) $numb_such++;
                $cur_len = 0;
                $open=0;
            }
        }
    }

    if(($cur_max_len!=0)&&($numb_such==0)) $numb_such=1;
    if($cur_max_len==0) $numb_such=1;
    fputs($stdout, $cur_max_len . " " . $numb_such);
?>

<?php

    // 5C - Наибольшая правильная скобочная подстрока

    $stdin = fopen('php://stdin', 'r');
    $start_string = "";
    echo "Enter string - ";
    fscanf($stdin, "%s\n", $start_string);
    $start_string_length = strlen($start_string);
    ////echo $start_string_length."\n";
    $str_begin = 0;
    $str_end = 0;
    $current_substr = "";
    $max_substring = ""; // здесь храним максимальную подстроку
    $flag_correct = 0; //признак корректности скобочной последовательности
    $number_correct = 0; //количество корректных подстрок в строке
    for($i=0; $i<$start_string_length; $i++) {
        //проверяем очередной символ и модифицируем значение флага
        if($start_string{$i}==")") {
            $flag_correct--;
        }
        else {
            if($flag_correct==0) {
                $str_begin = $i;
            }
            $flag_correct++;
        }
        ////echo $start_string{$i}."\n";
        echo $flag_correct."\n";
        //
        if($flag_correct<0) {
            $flag_correct=0;
        }
        elseif($flag_correct==0) {
            $str_end = $i+1;
            $current_substr = substr($start_string, $str_begin, $str_end-$str_begin);
            if(($str_end-$str_begin)>(strlen($max_substring))) {
                $max_substring = $current_substr;
            }
            $number_correct++;
        }
        // if(($flag_correct==0)&&($start_string{$i}==")")) {
            // $str_end = $i+1;
            // $current_substr = substr($start_string, $str_begin, $str_end-$str_begin);
            // // echo $current_substr."\n";
            // // echo $str_begin."\n";
            // // echo $str_end."\n";
            // // echo "---------------\n";
            // if(strlen($current_substr)>strlen($max_substring)) {
                // $max_substring = $current_substr;
            // }
            // //echo $max_substring."\n";
            // $str_begin = $i;
            // $number_correct++;
        // }
        // // // elseif(($flag_correct==1)&&($i==0)) {
            // // // $str_begin = $i;
        // // // }
        // elseif($flag_correct==0) {
            // $str_begin = $i;
        // }
        // elseif($flag_correct<0) {
            // $flag_correct=0;
            // //continue;
        // }
    }

    if($number_correct>0) {
        echo $max_substring." ".$number_correct."\n";
    }
    else {
        echo "0 1\n";
    }
    fclose($stdin);
?>

<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $string = fgets($stdin);

    $string = rtrim($string, "\n");
    $numb_such = 0;
    $cur_max_len = 0;
    $cur_len = 0;
    $open=0;
    for($i=0;$i<strlen($string);++$i){
        if($string[$i]=="(") $open++;
        else $open--;

        $cur_len++;

        if($open < 0){
            if(($cur_len-1)>$cur_max_len) $cur_max_len = $cur_len-1;
            else if(($cur_len-1) == $cur_max_len) $numb_such++;
            $cur_len = 0;
            $open=0;
        }
    }

    if($open>0){
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $string[$i]=")";
            else $string[$i]="(";
        }

        $string = substr(strrev($string), 0, $cur_len-1);
    //    echo "\n" . $string;

        $cur_len = 0;
        $open=0;
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $open++;
            else $open--;

            $cur_len++;

            if($open < 0){
                if(($cur_len-1)>$cur_max_len) $cur_max_len = $cur_len-1;
                else if(($cur_len-1) == $cur_max_len) $numb_such++;
                $cur_len = 0;
                $open=0;
            }
        }
    }

    if($cur_max_len==0) $numb_such=1;
    fputs($stdout, $cur_max_len . " " . $numb_such);
?>

<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $string = fgets($stdin);

    $numb_such = 0;
    $cur_max_len = 0;
    $cur_len = 0;
    $open=0;
    for($i=0;$i<strlen($string);++$i){
        if($string[$i]=="(") $open++;
        else $open--;

        $cur_len++;

        if($open < 0){
            if(($cur_len-1)>$cur_max_len) {
                $cur_max_len = $cur_len-1;
                $numb_such=1;
            }
            else if(($cur_len-1) == $cur_max_len) $numb_such++;
            $cur_len = 0;
            $open=0;
        }
    }

    if($open>0){
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $string[$i]=")";
            else $string[$i]="(";
        }

        $string = substr(strrev($string), 1, $cur_len) . "\n";

        $cur_len = 0;
        $open=0;
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $open++;
            else $open--;

            $cur_len++;

            if($open < 0){
                if(($cur_len-1)>$cur_max_len) {
                    $cur_max_len = $cur_len-1;
                    $numb_such=1;
                }
                else if(($cur_len-1) == $cur_max_len) $numb_such++;
                $cur_len = 0;
                $open=0;
            }
        }
    }

    if(($cur_max_len!=0)&&($numb_such==0)) $numb_such=1;
    if($cur_max_len==0) $numb_such=1;
    fputs($stdout, $cur_max_len . " " . $numb_such);
?>

<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $string = fgets($stdin);

    $numb_correct = 0;
    $cur_max_len = 0;
    $cur_len = 0;
    $open=0;
    for($i=0;$i<strlen($string);++$i){
        if($string[$i]=="(") $open++;
        else $open--;

        $cur_len++;

        if($open < 0){
            if(($cur_len-1)>$cur_max_len) $cur_max_len = $cur_len-1;
            if(($cur_len-1)>0) $numb_correct++;
            $cur_len = 0;
            $open=0;
        }
    }
    if($cur_max_len==0) $numb_correct=1;
    fputs($stdout, $cur_max_len . " " . $numb_correct);
?>

<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $string = fgets($stdin);

    $string = rtrim($string, "\n");
    $numb_such = 0;
    $cur_max_len = 0;
    $cur_len = 0;
    $open=0;
    for($i=0;$i<strlen($string);++$i){
        if($string[$i]=="(") $open++;
        else $open--;

        $cur_len++;

        if($open < 0){
            if(($cur_len-1)>$cur_max_len) $cur_max_len = $cur_len-1;
            else if(($cur_len-1) == $cur_max_len) $numb_such++;
            $cur_len = 0;
            $open=0;
        }
    }

    if($open>0){
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $string[$i]=")";
            else $string[$i]="(";
        }

        $string = substr(strrev($string), 0, $cur_len-1);

        $cur_len = 0;
        $open=0;
        for($i=0;$i<strlen($string);++$i){
            if($string[$i]=="(") $open++;
            else $open--;

            $cur_len++;

            if($open < 0){
                if(($cur_len-1)>$cur_max_len) $cur_max_len = $cur_len-1;
                else if(($cur_len-1) == $cur_max_len) $numb_such++;
                $cur_len = 0;
                $open=0;
            }
        }
    }

    if(($cur_max_len!=0)&&($numb_such==0)) $numb_such=1;
    if($cur_max_len==0) $numb_such=1;
    fputs($stdout, $cur_max_len . " " . $numb_such);
?>


A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You are given an integer $$$n$$$. Your goal is to construct and print exactly $$$n$$$ different regular bracket sequences of length $$$2n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 50$$$).

For each test case, print $$$n$$$ lines, each containing a regular bracket sequence of length exactly $$$2n$$$. All bracket sequences you output for a testcase should be different (though they may repeat in different test cases). If there are multiple answers, print any of them. It can be shown that it's always possible.

<?php declare(strict_types = 1);

$t = intval(fgets(STDIN));
while ($t--) {
	$n = intval(fgets(STDIN));
	for ($i = 0; $i < $n; $i++) {
		for ($j = 0; $j < $i; $j++) {
			echo "()";
		}
		for ($j = $i; $j < $n; $j++) {
			echo "(";
		}
		for ($j = $i; $j < $n; $j++) {
			echo ")";
		}
		echo "\n";
	}
}

<?php

$n = intval(trim(fgets(STDIN)));
for ($i = 1; $i <= $n; $i++) {
    $inp = intval(trim(fgets(STDIN)));
    $result = []; $max = $inp * 2;
    for ($y = 1; $y <= $inp; $y++) {
        $str = str_repeat('(', $y);
        $str = $str . str_repeat(')(',($inp - $y));
        $str = $str . str_repeat(')', $y );
        echo $str;
        echo "\n";
    }

}

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

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

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

}

//$iQueryCount = 1;
$iQueryCount = IO::str();
$aAllResults = [];
while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $n = IO::str();
    for ($i = 1; $i <= $n; $i++) {
        $str = $str2 = '';
        for ($j = 0; $j < $i; $j++) {
            $str .= '(';
            $str2 .= ')';
        }
        $r = $str . $str2;
        for ($x = 0; $x < $n - $i; $x++) {
            $r .= '()';
        }
        IO::line($r);
    }

}

?>


A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≤ pi ≤ n).A lucky permutation is such permutation p, that any integer i (1 ≤ i ≤ n) meets this condition ppi = n - i + 1.You have integer n. Find some lucky permutation p of size n.

The first line contains integer n (1 ≤ n ≤ 105) — the required permutation size.

Print "-1" (without the quotes) if the lucky permutation p of size n doesn't exist. Otherwise, print n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) after a space — the required permutation. If there are multiple answers, you can print any of them.

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

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

if (($n % 4 == 2) || ($n % 4 == 3)) {echo "-1"; exit;}

if ($n % 4 == 1) {
	$r = ($n - 1)/4;
	for ($i = 1; $i <= $r; $i++) {
		$odd = 2*$i - 1;
		$even = 2*$i;
		$arr[$odd] = $even;
		$arr[$even] = $n+1 - $odd;
		$arr[$n+1 - $odd] = $n+1 - $even;
		$arr[$n+1 - $even] = $odd;
	}
	$arr[($n+1)/2] = ($n+1)/2;
}

if ($n % 4 == 0) {
	$r = $n/4;
	for ($i = 1; $i <= $r; $i++) {
		$odd = 2*$i - 1;
		$even = 2*$i;
		$arr[$odd] = $even;
		$arr[$even] = $n+1 - $odd;
		$arr[$n+1 - $odd] = $n+1 - $even;
		$arr[$n+1 - $even] = $odd;
	}
}

for ($i = 1; $i <= $n; $i++) {
	echo $arr[$i] . " ";
}

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


This is an easy version of the problem. The only difference between an easy and a hard version is the constraints on $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$.You are given $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ with $$$a < c$$$ and $$$b < d$$$. Find any pair of numbers $$$x$$$ and $$$y$$$ that satisfies the following conditions: $$$a < x \leq c$$$, $$$b < y \leq d$$$, $$$x \cdot y$$$ is divisible by $$$a \cdot b$$$.Note that required $$$x$$$ and $$$y$$$ may not exist.

The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10$$$), the number of test cases. The descriptions of the test cases follow. The only line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$1 \leq a < c \leq 10^5$$$, $$$1 \leq b < d \leq 10^5$$$).

For each test case print a pair of numbers $$$a < x \leq c$$$ and $$$b < y \leq d$$$ such that $$$x \cdot y$$$ is divisible by $$$a \cdot b$$$. If there are multiple answers, print any of them. If there is no such pair of numbers, then print -1 -1.


Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.

The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input.

Print a single integer — the maximum possible total length of words in Andrew's article.

NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}.

<?php
//$file = fopen('input.in', 'r');
$file = STDIN;
$n = trim(fgets($file));
$aArray = array_fill(0, 26, 0);
$bArray = array_fill(0, 26, $aArray);
for ($i = 0; $i < $n; $i++) {
    $s = count_chars(trim(fgets($file)), 1);
    $c = count($s);
    if ($c > 2) {
        continue;
    } elseif ($c == 2) {
        $temp = array();
        $f = 0;
        foreach ($s as $l => $t) {
            $temp[] = $l - 97;
            $f += $t;
        }
        $bArray[$temp[0]][$temp[1]] += $f;
        $bArray[$temp[1]][$temp[0]] += $f;

    } else {
        foreach ($s as $l => $t) {
            $aArray[$l - 97] += $t;
        }
    }
}
$max = 0;
for ($i = 0; $i < 26; $i++) {
    for ($j = 0; $j < 26; $j++) {
        if ($i==$j) {
            continue;
        }
        $max = max($max, $bArray[$i][$j] + $aArray[$i] + $aArray[$j]);
    }
}
echo $max;


You are given a set $$$S$$$, which contains the first $$$n$$$ positive integers: $$$1, 2, \ldots, n$$$.You can perform the following operation on $$$S$$$ any number of times (possibly zero):   Choose a positive integer $$$k$$$ where $$$1 \le k \le n$$$, such that there exists a multiple of $$$k$$$ in $$$S$$$. Then, delete the smallest multiple of $$$k$$$ from $$$S$$$. This operation requires a cost of $$$k$$$. You are given a set $$$T$$$, which is a subset of $$$S$$$. Find the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$. We can show that such a transformation is always possible.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The description of the test cases follows. The first line contains a single positive integer $$$n$$$ ($$$1 \le n \le 10^6$$$). The second line of each test case contains a binary string of length $$$n$$$, describing the set $$$T$$$. The $$$i$$$-th character of the string is '1' if and only if $$$i$$$ is an element of $$$T$$$, and '0' otherwise. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.

For each test case, output one non-negative integer — the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$.

NoteIn the first test case, we shall not perform any operations as $$$S$$$ is already equal to $$$T$$$, which is the set $$$\{1, 2, 3, 4, 5, 6\}$$$.In the second test case, initially, $$$S = \{1, 2, 3, 4, 5, 6, 7\}$$$, and $$$T = \{1, 2, 4, 7\}$$$. We shall perform the following operations:   Choose $$$k=3$$$, then delete $$$3$$$ from $$$S$$$.  Choose $$$k=3$$$, then delete $$$6$$$ from $$$S$$$.  Choose $$$k=5$$$, then delete $$$5$$$ from $$$S$$$. The total cost is $$$3+3+5 = 11$$$. It can be shown that this is the smallest cost possible.In the third test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{\}$$$ (empty set). We shall perform $$$4$$$ operations of $$$k=1$$$ to delete $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$.In the fourth test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{3\}$$$. We shall perform two operations with $$$k=1$$$ to delete $$$1$$$ and $$$2$$$, then perform one operation with $$$k=2$$$ to delete $$$4$$$.

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

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

   $n = IO::get();
      $s = IO::get();
     $s = ' '. $s;
      $ans = 0;
      $it = 0;

   for($i=1; $i <= $n; $i++) {
     for($j=$i; $j <= $n; $j+=$i) {
           if($s[$j] == 1 ) {
                break;
           }
           if($s[$j] == 0) {
                $ans +=$i;
                $s[$j] = 2;
           }
     }
   }

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

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

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

   $n = IO::get();
      $s = IO::get();
      $t = [];
      $ans = 0;
   for($i=0; $i < $n; $i++) {
     if($s[$i] == 0) {
         $t[] = $i+1;
     }
   }
//    IO::prArray($t);
   if(count($t) > 0) {
        $size = count($t);
      for($i=0; $i < count($t); $i++) {
           if(isset($t[$i])) {
               $temp = $t[$i];
               $ans += $temp;
               for($j=$i+1; $j < $size; $j++) {

                    if(isset($t[$j]) && $t[$j] % $temp == 0) {
                         //  IO::pr($j . ' => ' . $t[$j] . ' ' . $temp);
                         $ans += $temp;
                         unset($t[$j]);
                         $t = array_values($t);
                    }
               }
               // if(count($t) == $i+1) {
               //      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;
    }
}

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

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

   $n = IO::get();
      $s = IO::get();
      $t = [];
      $ans = 0;
   for($i=0; $i < $n; $i++) {
     if($s[$i] == 0) {
         $t[] = $i+1;
     }
   }
    IO::prArray($t);
   if(count($t) > 0) {
        $size = count($t);
      for($i=0; $i < count($t); $i++) {
           if(isset($t[$i])) {
               $temp = $t[$i];
               $ans += $temp;
               for($j=$i+1; $j < $size; $j++) {

                    if(isset($t[$j]) && $t[$j] % $temp == 0) {
                         //  IO::pr($j . ' => ' . $t[$j] . ' ' . $temp);
                         $ans += $temp;
                         unset($t[$j]);
                         $t = array_values($t);
                    }
               }
               // if(count($t) == $i+1) {
               //      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;
    }
}


Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that:  the cashier needs 5 seconds to scan one item;  after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.

The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 ≤ ki ≤ 100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 ≤ mi, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.

Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.

NoteIn the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
$f = array();
for($x = 1; $x <= $a; $x++)
{
    $c = explode(" ", trim(fgets(STDIN)));
    $e = 0;
    $d = array_sum($c);
    $e = ($d * 5) + (count($c) * 15);
    array_push($f, $e);
}
sort($f);
print $f[0];
?>

<?php
define('LOCAL_ENV', false);
if (LOCAL_ENV) {
    error_reporting(E_ALL & !E_NOTICE);
//    $test = <<<INPUT
//4.147 2.8819
//6
//INPUT;
    $test = <<<INPUT
4
1 4 3 2
100
1 2 2 3
1 9 1
7 8
INPUT;
    $stdin = fopen('php://temp/in', 'rw');
    fwrite($stdin, $test);
    rewind($stdin);
} else {
    error_reporting(0);
    $stdin = STDIN;
}
define('MY_STDIN', $stdin);

$n = (int) trim(fgets(MY_STDIN));
$k = explode(' ', trim(fgets(MY_STDIN)));
$min = PHP_INT_MAX;
for ($i = 0; $i < $n; $i++) {
    $m = explode(' ', trim(fgets(MY_STDIN)));
    $cur = 0;
    foreach ($m as $cnt) {
        $cur += $cnt * 5 + 15;
    }
    $min = min($min, $cur);
}

echo $min;

<?php

$ncash = trim(fgets(STDIN));
$nqueue = explode(" ", trim(fgets(STDIN)));

$m = PHP_INT_MAX;
for($i = 0; $i < $ncash; $i++)
{
	$nitems = explode(" ", trim(fgets(STDIN)));
	$qq = 15 * sizeof($nitems);
	for($j = 0; $j < sizeof($nitems); $j++)
		$qq += ($nitems[$j] * 5);

	$m = min($m, $qq);
}

echo $m . PHP_EOL;


Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to n was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal — compare the second, and so on. If we have two permutations x and y, then x is lexicographically smaller if xi < yi, where i is the first index in which the permutations x and y differ.Determine the array Ivan will obtain after performing all the changes.

The first line contains an single integer n (2 ≤ n ≤ 200 000) — the number of elements in Ivan's array. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n) — the description of Ivan's array.

In the first line print q — the minimum number of elements that need to be changed in Ivan's array in order to make his array a permutation. In the second line, print the lexicographically minimal permutation which can be obtained from array with q changes.

NoteIn the first example Ivan needs to replace number three in position 1 with number one, and number two in position 3 with number four. Then he will get a permutation [1, 2, 4, 3] with only two changed numbers — this permutation is lexicographically minimal among all suitable. In the second example Ivan does not need to change anything because his array already is a permutation.


There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.

The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000,  - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.

Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers.

NoteExplanation to the first and second samples from the statement, respectively:

<?php
list ($n, $x0, $y0) = explode(' ', trim(fgets(STDIN)));
$xy = array();
for ($i = 0; $i < $n; $i++) {
  $xy[] = explode(' ', trim(fgets(STDIN)));
}

$count = 0;
while (!empty($xy)) {
  list ($x1, $y1) = array_shift($xy);

  $x1mx0 = $x1 - $x0;
  $y1my0 = $y1 - $y0;

  foreach ($xy as $i2 => $xy2) {
    list ($x2, $y2) = $xy2;
    if (abs($y1my0 * ($x2 - $x0) - $x1mx0 * ($y2 - $y0)) < 1e-8) {
      unset($xy[$i2]);
    }
  }

  $count++;
}

echo "$count\n";

<?php

$f = fopen('php://stdin', 'r');
//$f = fopen('test.txt', 'r');

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

list($n,$x,$y) = explode(" ",$s);

$res = array();

$dop = 0;

for($i=0;$i<$n;$i++){
    list($a,$b) = explode(" ",trim(fgets($f)));

    if (($b-$y) == 0) {
        $dop = 1;
        continue;
    }

    $tan = ($a-$x)/($b-$y);
    $res["$tan"] = 1;

}

echo count($res)+$dop;


Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of actions Valentin did. The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types:    Valentin pronounced some word and didn't get an electric shock. This action is described by the string ". w" (without quotes), in which "." is a dot (ASCII-code 46), and w is the word that Valentin said.  Valentin pronounced some word and got an electric shock. This action is described by the string "! w" (without quotes), in which "!" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said.  Valentin made a guess about the selected letter. This action is described by the string "? s" (without quotes), in which "?" is a question mark (ASCII-code 63), and s is the guess — a lowercase English letter.  All words consist only of lowercase English letters. The total length of all words does not exceed 105. It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after pronouncing some word, then it contains the selected letter; and also if Valentin didn't get an electric shock after pronouncing some word, then it does not contain the selected letter.

Output a single integer — the number of electric shocks that Valentin could have avoided if he had told the selected letter just after it became uniquely determined.

8
! hello
! codeforces
? c
. o
? d
? h
. l
? e

7
! ababahalamaha
? a
? b
? a
? b
? a
? h

NoteIn the first test case after the first action it becomes clear that the selected letter is one of the following: a, b, c. After the second action we can note that the selected letter is not a. Valentin tells word "b" and doesn't get a shock. After that it is clear that the selected letter is c, but Valentin pronounces the word cd and gets an excessive electric shock. In the second test case after the first two electric shocks we understand that the selected letter is e or o. Valentin tries some words consisting of these letters and after the second word it's clear that the selected letter is e, but Valentin makes 3 more actions before he makes a correct hypothesis.In the third example the selected letter can be uniquely determined only when Valentin guesses it, so he didn't get excessive electric shocks.

<?php
$a = trim(fgets(STDIN));
$b = 0;
$c = array();
for($x = 0; $x < $a; $x++)
{
     list($d, $e) = explode(" ", trim(fgets(STDIN)));
     if($d == ".")
     {
          $h = array_unique(str_split($e));
          sort($h);
          for($y = 0; $y < count($c); $y++)
          {
               for($z = 0; $z < count($h); $z++)
               {
                    if($c[$y] == $h[$z])
                    {
                         unset($c[$y]);
                         break;
                    }
               }
          }
          if(count($c) == 1)
          {
               define(g, $b);
          }
     }
     elseif($d == "!")
     {
          $b++;
          if(count($c) == 0)
          {
               $c2 = array_unique(str_split($e));
               sort($c2);
               $c = $c2;
          }
          else
          {
               $f = array_unique(str_split($e));
               sort($f);
               $c = array_intersect($c, $f);
               if(count($c) == 1)
               {
                    define(g, $b);
               }
          }
     }
     elseif($d == "?")
     {
          $b++;
          for($y = 0; $y < count($c); $y++)
          {
               if($c[$y] == $e)
               {
                    unset($c[$y]);
               }
          }
          if(count($c) == 1)
          {
               define(g, $b);
          }
     }
     sort($c);
}
if(count($c) > 1)
{
     print "0";
}
else
{
     print ($b - 1) - g;
}
?>


В самолёте есть n рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа.Известно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, которые часто летают) и обычные. Перед вами стоит задача рассадить ещё k обычных пассажиров так, чтобы суммарное число соседей у статусных пассажиров было минимально возможным. Два пассажира считаются соседями, если они сидят в одном ряду и между ними нет других мест и прохода между рядами. Если пассажир является соседним пассажиром для двух статусных пассажиров, то его следует учитывать в сумме соседей дважды.

В первой строке следуют два целых числа n и k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10·n) — количество рядов мест в самолёте и количество пассажиров, которых нужно рассадить. Далее следует описание рядов мест самолёта по одному ряду в строке. Если очередной символ равен '-', то это проход между рядами. Если очередной символ равен '.', то это свободное место. Если очередной символ равен 'S', то на текущем месте будет сидеть статусный пассажир. Если очередной символ равен 'P', то на текущем месте будет сидеть обычный пассажир.  Гарантируется, что количество свободных мест не меньше k. Гарантируется, что все ряды удовлетворяют описанному в условии формату.

В первую строку выведите минимальное суммарное число соседей у статусных пассажиров. Далее выведите план рассадки пассажиров, который минимизирует суммарное количество соседей у статусных пассажиров, в том же формате, что и во входных данных. Если в свободное место нужно посадить одного из k пассажиров, выведите строчную букву 'x' вместо символа '.'.

4 9
PP.-PPPS-S.S
PSP-PPSP-.S.
.S.-S..P-SS.
P.S-P.PP-PSP

15
PPx-PPPS-S.S
PSP-PPSP-xSx
xSx-SxxP-SSx
P.S-PxPP-PSP

ПримечаниеВ первом примере нужно посадить ещё двух обычных пассажиров. Для минимизации соседей у статусных пассажиров, нужно посадить первого из них на третье слева место, а второго на любое из оставшихся двух мест, так как независимо от выбора места он станет соседом двух статусных пассажиров. Изначально, у статусного пассажира, который сидит на самом левом месте уже есть сосед. Также на четвёртом и пятом местах слева сидят статусные пассажиры, являющиеся соседями друг для друга (что добавляет к сумме 2).Таким образом, после посадки ещё двух обычных пассажиров, итоговое суммарное количество соседей у статусных пассажиров станет равно пяти.

<?php
$arr = explode(" ", fgets(STDIN));
$row_count = $arr[0];
$people_count = $arr[1];
$arRows = [];
for($i = 0; $i < $row_count; $i++){
    $arRows[] = fgets(STDIN);
}

//NOT S

foreach ($arRows as $key => $row){
    $arrStr = str_split($row);
    $srt_return = '';
    foreach ($arrStr as $k => $char){
        if($char == ".") {
            if ($people_count > 0) {
                if ($k >=1 && $k < 11) {
                    if ($arrStr[$k - 1] != "S" && $arrStr[$k + 1] != "S") {
                        $char = "x";
                        $people_count = $people_count - 1;
                    }

                }
                elseif($k == 0 && $arrStr[$k + 1] != "S") {
                    $char = "x";
                    $people_count = $people_count - 1;
                }
                elseif($k == 11 && $arrStr[$k - 1] != "S") {
                    $char = "x";
                    $people_count = $people_count - 1;
                }
            }
        }

        $srt_return = $srt_return.$char;
    }
    $arRows[$key] = $srt_return;

}

foreach ($arRows as $key => $row){
    $arrStr = str_split($row);
    $srt_return = '';
    foreach ($arrStr as $k => $char){
        if($char == ".") {
            if ($people_count > 0) {
                if ($k >=1 && $k < 11) {
                    $sos = $arrStr[$k - 1] . $arrStr[$k + 1];
                    if ($sos != "SS") {
                        $char = "x";
                        $people_count = $people_count - 1;
                    }

                }
                else {
                    $char = "x";
                    $people_count = $people_count - 1;
                }
            }
        }

        $srt_return = $srt_return.$char;
    }
    $arRows[$key] = $srt_return;

}

foreach ($arRows as $k => $row){

    if($people_count >= 1){
        $arRows[$k] = preg_replace("/\./","x",$arRows[$k],$people_count,$count);
        $people_count = $people_count - $count;
    }
    else{
        break;
    }

}
global $count_result;
$count_result = 0;
function counter($f){
    global $count_result;
    if($f != ""){
        if($f != "-" && $f != "."){
            $count_result++;
        }
    }

}

foreach ($arRows as $key => $row){
    $arrStr = str_split($row);
    foreach ($arrStr as $k => $char){
        if($char == "S"){
            if($k > 0){
                counter($arrStr[$k-1]);
            }
            if($k < 11){
                counter($arrStr[$k+1]);
            }
        }
    }
}

echo $count_result."\n";
foreach ($arRows as $row){
    echo $row;
}

?>

<?php
function sorting($str, $row, $colomn){
	global $neighbors;
	global $best_place, $mid_place, $bad_place;
    for($i = 0; $i < strlen($str); $i++){
    	if($str[$i] == "S"){
    		if($i > 0 && $str[$i-1] != "."){
    			$neighbors++;
    		}
    		if($i< strlen($str)-1 && $str[$i+1]!="."){
    			$neighbors++;
    		}
    	}
    	if($str[$i] == "."){
    		$c = 0;
    		if($i>0 && $str[$i-1]=="S"){
    			$c++;
    		}
    		if($i+1 < strlen($str) && $str[$i+1]=="S"){
    			$c++;
    		}
    		switch ($c) {
    			case 0:
    				$best_place[] = [$row, $i+$colomn];
    				break;
    			case 1:
    				$mid_place[] = [$row, $i+$colomn];
    				break;
    			case 2:
    				$bad_place[] = [$row, $i+$colomn];
    		}
    	}
    }
}
$list = explode(" ", fgets(STDIN));
$n = $list[0];
$passangers = $list[1];
$best_place = [];
$mid_place = [];
$bad_place = [];
$need_place = [];
$neighbors = 0;
$rows = [];
for($i = 0; $i < $n; $i++){
	$row = trim(fgets(STDIN));
	$rows[] = $row;
	$rows_in_row = explode("-", $row);
	$r1 = $rows_in_row[0];
	$r2 = $rows_in_row[1];
	$r3 = $rows_in_row[2];
    sorting($r1, $i, 0);
    sorting($r2, $i, 4);
    sorting($r3, $i, 9);
}
$best = count($best_place);
$mid = count($mid_place);
$bad = count($bad_place);
if($best >= $passangers){
	$need_place = array_slice($best_place, 0, $passangers);
}
else{
    $need_place = $best_place;
    $passangers -= $best;
    if($passangers <= $mid){
    	$need_place = array_merge($need_place, array_slice($mid_place, 0, $passangers));
        $neighbors += $passangers;
    }
    else{
    	$neighbors += $mid;
    	$passangers-=$mid;
    	$need_place = array_merge($need_place, $mid_place, array_slice($bad_place, 0, $passangers));
    	$neighbors += 2*$passangers;
    }
}
foreach ($need_place as $place) {
	$rows[$place[0]][$place[1]] = "x";
}
echo $neighbors;
foreach ($rows as $row) {
	echo "\n".$row;
}
?>

<?php
$arr = explode(" ", fgets(STDIN));
$row_count = $arr[0];
$people_count = $arr[1];
$arRows = [];
for($i = 0; $i < $row_count; $i++){
    $arRows[] = fgets(STDIN);
}
$arFirstPaterns = array(
    "/P\.-S/" => "Px-S",
    "/S-\.P/" => "S-xP",
    "/P\.-/" => "Px-",
    "/P\.P/" => "PxP",
    "/\.\.P/" => ".xP",
    "/P\.\./" => "Px.",
    "/^\.P/" => "xP",
    "/P\.$/" => "Px"
);

$arSecondPaterns = array(
    "/\.\.S/" =>".xS",
    "/S\.\./" =>"Sx.",
    "/-\.S/"=> "-xS",
    "/S\.-/"=> "Sx-",
    "/S\.$/" =>"Sx",
    "/^\.S/" =>"xS",
    "/P\.S/"=> "PxS",
    "/S\.P/"=> "SxP",
);

$count = 0;
foreach ($arRows as $k => $row){
    if($people_count >= 2){
        $maxDuble = intval($people_count / 2);
        $arRows[$k] = preg_replace("/P\.\.P/","PxxP",$arRows[$k]);
        $people_count -= ($count * 2);
    }
    else{
        break;
    }

}

$count = 0;
foreach ($arRows as $k => $row){
    foreach ($arFirstPaterns as $search => $replace){
        if($people_count >= 1){
            $arRows[$k] = preg_replace($search,$replace,$arRows[$k],$people_count,$count);
            $people_count -= $count;
        }
        else{
            break 2;
        }
    }
}
$count = 0;
foreach ($arRows as $k => $row){
    foreach ($arSecondPaterns as $search => $replace){
        if($people_count >= 1){
            $arRows[$k] = preg_replace($search,$replace,$arRows[$k],$people_count,$count);
            $people_count -= $count;
        }
        else{
            break 2;
        }
    }
}

foreach ($arRows as $key => $row){
    $arrStr = str_split($row);
    $srt_return = '';
    foreach ($arrStr as $k => $char){
        if($char == ".") {
            if ($people_count > 0) {
                if ($k >=1 && $k < 11) {
                    $sos = $arrStr[$k - 1] . $arrStr[$k + 1];
                    if ($sos != "SS") {
                        $char = "x";
                        $people_count--;
                    }

                }
                else {
                    $char = "x";
                    $people_count--;
                }
            }
        }

        $srt_return = $srt_return.$char;
    }
    $arRows[$key] = $srt_return;

}

foreach ($arRows as $k => $row){

    if($people_count >= 1){
        $arRows[$k] = preg_replace("/\./","x",$arRows[$k],$people_count,$count);
        $people_count -= $count;
    }
    else{
        break;
    }

}
global $count_result;
$count_result = 0;
function counter($f){
    global $count_result;
    if($f != ""){
        if($f != "-" && $f != "."){
            $count_result++;
        }
    }

}

foreach ($arRows as $key => $row){
    $arrStr = str_split($row);
    foreach ($arrStr as $k => $char){
        if($char == "S"){
            if($k > 0){
                counter($arrStr[$k-1]);
            }
            if($k < 11){
                counter($arrStr[$k+1]);
            }
        }
    }
}

echo $count_result."\n";
foreach ($arRows as $row){
    echo $row;
}

?>

<?php
list($count, $range) = explode(" ", fgets(STDIN));
$count = (int) $count;
$range = (int) $range;
$arr = explode(" ", fgets(STDIN));
$velo = 0;

$pos = $arr[0];
for($i = 1; $i < $count; $i++){
    if($arr[$i] > $pos){
    	$pos = $arr[$i-1] + $range;
		if($arr[$i] > $pos){
			$velo = -1;
			break;
		} else {$velo ++;}
    }
}
echo $velo."  ";

<?php
function sorting($str, $row, $colomn){
	global $neighbors;
	global $best_place, $mid_place, $bad_place;
    for($i = 0; $i < strlen($str); $i++){
    	if($str[$i] == "S"){
    		if($i > 0 && $str[$i-1] != "."){
    			$neighbors++;
    		}
    		if($i< strlen($str)-1 && $str[$i+1]!="."){
    			$neighbors++;
    		}
    	}
    	if($str[$i] == "."){
    		$c = 0;
    		if($i>0 && $str[$i-1]=="S"){
    			$c++;
    		}
    		if($i+1 < strlen($str) && $str[$i+1]=="S"){
    			$c++;
    		}
    		switch ($c) {
    			case 0:
    				$best_place[] = [$row, $i+$colomn];
    				break;
    			case 1:
    				$mid_place[] = [$row, $i+$colomn];
    				break;
    			case 2:
    				$bad_place[] = [$row, $i+$colomn];
    		}
    	}
    }
}
$list = explode(" ", fgets(STDIN));
$n = $list[0];
$passangers = $list[1];
$best_place = [];
$mid_place = [];
$bad_place = [];
$need_place = [];
$neighbors = 0;
$rows = [];
for($i = 0; $i < $n; $i++){
	$row = trim(fgets(STDIN));
	$rows[] = $row;
	$rows_in_row = explode("-", $row);
	$r1 = $rows_in_row[0];
	$r2 = $rows_in_row[1];
	$r3 = $rows_in_row[2];
    sorting($r1, $i, 0);
    sorting($r2, $i, 4);
    sorting($r3, $i, 9);
}
$best = count($best_place);
$mid = count($mid_place);
$bad = count($bad_place);
echo "neig $neighbors \n";
if($best >= $passangers){
	$need_place = array_slice($best_place, 0, $passangers);
}
else{
    $need_place = $best_place;
    $passangers -= $best;
    if($passangers <= $mid){
    	$need_place = array_merge($need_place, array_slice($mid_place, 0, $passangers));
        $neighbors += $passangers;
    }
    else{
    	$neighbors += $mid;
    	$passangers-=$mid;
    	$need_place = array_merge($need_place, $mid_place, array_slice($bad_place, 0, $passangers));
    	$neighbors += 2*$passangers;
    }
}
foreach ($need_place as $place) {
	$rows[$place[0]][$place[1]] = "x";
}
echo $neighbors."\n";
foreach ($rows as $row) {
	echo $row."\n";
}
//echo "best";
//var_dump($best_place);
//echo "\n mid";
//var_dump($mid_place);
//echo "\n bad";
//var_dump($bad_place);
?>


A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.

You are given four integers V1, V2, V3, Vm(1 ≤ Vi ≤ 100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1 > V2 > V3.

Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively. If there are multiple possible solutions, print any. If there is no solution, print "-1" (without quotes).

NoteIn first test case all conditions for cars' sizes are satisfied.In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20.


You are given a sequence of integers of length $$$n$$$ and integer number $$$k$$$. You should print any integer number $$$x$$$ in the range of $$$[1; 10^9]$$$ (i.e. $$$1 \le x \le 10^9$$$) such that exactly $$$k$$$ elements of given sequence are less than or equal to $$$x$$$.Note that the sequence can contain equal elements.If there is no such $$$x$$$, print "-1" (without quotes).

The first line of the input contains integer numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le n$$$). The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the sequence itself.

Print any integer number $$$x$$$ from range $$$[1; 10^9]$$$ such that exactly $$$k$$$ elements of given sequence is less or equal to $$$x$$$. If there is no such $$$x$$$, print "-1" (without quotes).

NoteIn the first example $$$5$$$ is also a valid answer because the elements with indices $$$[1, 3, 4, 6]$$$ is less than or equal to $$$5$$$ and obviously less than or equal to $$$6$$$.In the second example you cannot choose any number that only $$$2$$$ elements of the given sequence will be less than or equal to this number because $$$3$$$ elements of the given sequence will be also less than or equal to this number.

<?php

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

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

$n = $input[0];
$k = $input[1];

sort($setOfNumbers);

if($k==0){
    if($setOfNumbers[0]<=1){
        print(-1);
    }
    else{
        print(1);
    }
}
else if($setOfNumbers[$k-1] == $setOfNumbers[$k]){
    print(-1);
}
else{
    print($setOfNumbers[$k-1]);
}

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = array();
for($x = 0; $x < $a; $x++)
{
     $d[$c[$x]]++;
}
ksort($d);
$e = array_keys($d);
$f = 0;
for($x = 0; $x < count($d); $x++)
{
     $f += $d[$e[$x]];
     if($f == $b)
     {
          print $e[$x];
          break;
     }
     elseif($f > $b)
     {
          print "-1";
          break;
     }
}
?>

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

<?php

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

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

$n = $input[0];
$k = $input[1];

sort($setOfNumbers);

if($k==0){
    if($setOfNumbers[0]<=1){
        print(-1);
    }
    else{
        print($setOfNumbers[0]);
    }
}
else if($setOfNumbers[$k-1] == $setOfNumbers[$k]){
    print(-1);
}
else{
    print($setOfNumbers[$k-1]);
}

<?php

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

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

$n = $input[0];
$k = $input[1];

sort($setOfNumbers);

if($setOfNumbers[$k-1] == $setOfNumbers[$k] || $k == 0){
    print(-1);
}
else{
    print($setOfNumbers[$k-1]);
}

<?php

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

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

$n = $input[0];
$k = $input[1];

sort($setOfNumbers);

if($setOfNumbers[$k-1] == $setOfNumbers[$k]){
    print(-1);
}
else{
    print($setOfNumbers[$k-1]);
}

<?php

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

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

$n = $input[0];
$k = $input[1];

sort($setOfNumbers);

if($k==1){
    if($setOfNumbers[0]<=1){
        print(-1);
    }
    else{
        print($setOfNumbers[0]);
    }
}
else if($setOfNumbers[$k-1] == $setOfNumbers[$k]){
    print(-1);
}
else{
    print($setOfNumbers[$k-1]);
}