Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
$c = trim(fgets(STDIN));
$d = explode(" ", trim(fgets(STDIN)));
$e = array();
for($x = 0; $x < $c; $x++)
{
    for($y = 0; $y < $a; $y++)
    {
        if($d[$x] % $b[$y] == 0)
        {
            array_push($e, $d[$x] / $b[$y]);
        }
    }
}
rsort($e);
array_push($e, "end");
$f = array_unique($e);
$g = array_keys($f);
print $g[1] - $g[0];
?>

<?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();
	}

	$M = (int)$Input->in();

	$max = -1;
	$c = 0;

	for ($i = 0; $i < $M; $i++)
	{
		$B = (int)$Input->in();

		foreach ($A as $a)
		{
			if ($B % $a === 0)
			{
				if ($max < intval($B / $a))
				{
					$max = intval($B / $a);
					$c = 1;
				}
				else if ($max === intval($B / $a))
				{
					$c++;
				}
			}
		}

	}

	print($c);
}

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

	}
}

?>

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

$max = 0;
$r = 0;
for($i=0;$i<$n;$i++)
 for($j=0;$j<$m;$j++)
  if($b[$j] % $a[$i] == 0)
   if($b[$j]/$a[$i] == $max) $r++; else {$max = $b[$j]/$a[$i]; $r = 1;}

print $r;
?>


Polycarp has to solve exactly $$$n$$$ problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in $$$k$$$ days. It means that Polycarp has exactly $$$k$$$ days for training!Polycarp doesn't want to procrastinate, so he wants to solve at least one problem during each of $$$k$$$ days. He also doesn't want to overwork, so if he solves $$$x$$$ problems during some day, he should solve no more than $$$2x$$$ problems during the next day. And, at last, he wants to improve his skill, so if he solves $$$x$$$ problems during some day, he should solve at least $$$x+1$$$ problem during the next day.More formally: let $$$[a_1, a_2, \dots, a_k]$$$ be the array of numbers of problems solved by Polycarp. The $$$i$$$-th element of this array is the number of problems Polycarp solves during the $$$i$$$-th day of his training. Then the following conditions must be satisfied:   sum of all $$$a_i$$$ for $$$i$$$ from $$$1$$$ to $$$k$$$ should be $$$n$$$;  $$$a_i$$$ should be greater than zero for each $$$i$$$ from $$$1$$$ to $$$k$$$;  the condition $$$a_i < a_{i + 1} \le 2 a_i$$$ should be satisfied for each $$$i$$$ from $$$1$$$ to $$$k-1$$$. Your problem is to find any array $$$a$$$ of length $$$k$$$ satisfying the conditions above or say that it is impossible to do it.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9, 1 \le k \le 10^5$$$) — the number of problems Polycarp wants to solve and the number of days Polycarp wants to train.

If it is impossible to find any array $$$a$$$ of length $$$k$$$ satisfying Polycarp's rules of training, print "NO" in the first line. Otherwise print "YES" in the first line, then print $$$k$$$ integers $$$a_1, a_2, \dots, a_k$$$ in the second line, where $$$a_i$$$ should be the number of problems Polycarp should solve during the $$$i$$$-th day. If there are multiple answers, you can print any.

<?php
# 1157D
declare(strict_types=1);

$start = microtime(true);

[$n, $k] = fscanf(STDIN, '%u %u');

if ($k === 1) {
    die('YES' . PHP_EOL . $n);
}
$summ = (int)($k * ($k + 1) / 2);

if ($summ > $n) {
    die('NO');
}

$arr = [];

for ($i = 0; $i < $k; $i++) {
    $arr[$i] = $i + 1;
}

$delta = (int)floor(($n - $summ) / $k);
if ($delta) {
    for ($i = 0; $i < $k; $i++) {
        $arr[$i] = $i + $delta;
    }
}

$n -= array_sum($arr);

$lastIndex = $k - 1;
while($n > 0) {
    $i = $lastIndex;
    while ($n > 0 && $i >= 0 && $arr[$i] < ($delta + $arr[0] * 2 ** $i)) {
        $arr[$i]++;
        $n--;
        $i--;
    }
    if ($arr[$lastIndex] === (int)($delta + $arr[0] * 2 ** $lastIndex)) {
        break;
    }
}
if ($n !== 0) {
    echo 'NO';
} else {
    echo 'YES' . PHP_EOL . implode(' ', $arr);
}


DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?

The first line contains a single string s (1 ≤ |s| ≤ 103). The second line contains a single integer k (0 ≤ k ≤ 103). The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.

Print a single integer — the largest possible value of the resulting string DZY could get.

NoteIn the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.

<?php

$s = trim(fgets(STDIN));
$k = (int)fgets(STDIN);
$values = array_map('intval', explode(' ', trim(fgets(STDIN))));
$index = array_search(max($values), $values);
$char = chr(ord('a') + $index);

for ($i = 0; $i < $k; $i++) {
	$s .= $char;
}

$res = 0;
for ($i = 0; $i < strlen($s); $i++) {
	$res += ($i+1) * $values[ord($s[$i])-ord('a')];
}

echo $res."\n";


You are given an array $$$a$$$ consisting of $$$n$$$ integers.Let's call a pair of indices $$$i$$$, $$$j$$$ good if $$$1 \le i < j \le n$$$ and $$$\gcd(a_i, 2a_j) > 1$$$ (where $$$\gcd(x, y)$$$ is the greatest common divisor of $$$x$$$ and $$$y$$$).Find the maximum number of good index pairs if you can reorder the array $$$a$$$ in an arbitrary way.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$) — the number of elements in the array. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.

For each test case, output a single integer — the maximum number of good index pairs if you can reorder the array $$$a$$$ in an arbitrary way.

NoteIn the first example, the array elements can be rearranged as follows: $$$[6, 3, 5, 3]$$$.In the third example, the array elements can be rearranged as follows: $$$[4, 4, 2, 1, 1]$$$.


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.

The single line contains an integer n (1 ≤ n ≤ 106) — the sum of digits of the required lucky number.

Print on the single line the result — the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.


$$$n$$$ students are taking an exam. The highest possible score at this exam is $$$m$$$. Let $$$a_{i}$$$ be the score of the $$$i$$$-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied:   All scores are integers  $$$0 \leq a_{i} \leq m$$$  The average score of the class doesn't change. You are student $$$1$$$ and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 200$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^{3}$$$, $$$1 \leq m \leq 10^{5}$$$)  — the number of students and the highest possible score respectively. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 0 \leq a_{i} \leq m$$$)  — scores of the students.

For each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._

NoteIn the first case, $$$a = [1,2,3,4] $$$, with average of $$$2.5$$$. You can change array $$$a$$$ to $$$[10,0,0,0]$$$. Average remains $$$2.5$$$, and all conditions are satisfied.In the second case, $$$0 \leq a_{i} \leq 5$$$. You can change $$$a$$$ to $$$[5,1,1,3]$$$. You cannot increase $$$a_{1}$$$ further as it will violate condition $$$0\le a_i\le m$$$.

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     list($b, $c) = explode(" ", trim(fgets(STDIN)));
     $d = explode(" ", trim(fgets(STDIN)));
     if($b == 1)
     {
          print $d[0] . "\n";
     }
     else
     {
          $e = array_sum(array_slice($d, 1));
          $d[0] += $e;
          if($d[0] < $c)
          {
               print $d[0] . "\n";
          }
          else
          {
               print $c . "\n";
          }
     }
}
?>

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t= trim(fgets($handle));
for($k=0;$k<$t;$k++)
{
    $h= trim(fgets($handle));
    $h=explode(' ',$h);
    $n=$h[0];$m=$h[1];
    $a= trim(fgets($handle));
    $a=explode(' ',$a);
    $sum=0;
    $max=0;
    foreach ($a as $b)
    {
        if($max<$b)
        {
            $max=$b;
        }
        $sum+=$b;
    }
    if($sum<$m)
        echo $sum."\n";
    else
        echo $m."\n";
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t= trim(fgets($handle));
for($k=0;$k<$t;$k++)
{
    $h= trim(fgets($handle));
    $h=explode(' ',$h);
    $n=$h[0];$m=$h[1];
    $a= trim(fgets($handle));
    $a=explode(' ',$a);
    echo $m."\n";
}


You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $$$n$$$ consecutive days. During the $$$i$$$-th day you have to write exactly $$$a_i$$$ names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $$$m$$$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $$$1$$$ to $$$n$$$.

The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ means the number of names you will write in the notebook during the $$$i$$$-th day.

Print exactly $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$, where $$$t_i$$$ is the number of times you will turn the page during the $$$i$$$-th day.

NoteIn the first example pages of the Death Note will look like this $$$[1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]$$$. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.


Cowboy Vlad has a birthday today! There are $$$n$$$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.Formally, let's number children from $$$1$$$ to $$$n$$$ in a circle order, that is, for every $$$i$$$ child with number $$$i$$$ will stand next to the child with number $$$i+1$$$, also the child with number $$$1$$$ stands next to the child with number $$$n$$$. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of the children who came to the cowboy Vlad's birthday. The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) denoting heights of every child.

Print exactly $$$n$$$ integers — heights of the children in the order in which they should stand in a circle. You can start printing a circle with any child. If there are multiple possible answers, print any of them.

NoteIn the first example, the discomfort of the circle is equal to $$$1$$$, since the corresponding absolute differences are $$$1$$$, $$$1$$$, $$$1$$$ and $$$0$$$. Note, that sequences $$$[2, 3, 2, 1, 1]$$$ and $$$[3, 2, 1, 1, 2]$$$ form the same circles and differ only by the selection of the starting point.In the second example, the discomfort of the circle is equal to $$$20$$$, since the absolute difference of $$$10$$$ and $$$30$$$ is equal to $$$20$$$.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
rsort($b);
$c = array($b[0]);
for($x = 1; $x < $a; $x++)
{
     if($x % 2 == 0)
     {
          array_unshift($c, $b[$x]);
     }
     else
     {
          array_push($c, $b[$x]);
     }
}
print implode(" ", $c);
?>


Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm:  Root the tree at node 1.  Count the number of nodes at an even depth. Let it be evenCnt.  Count the number of nodes at an odd depth. Let it be oddCnt.  The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.

The only line contains an integer n (2 ≤ n ≤ 105), the number of nodes in the desired trees.

The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only. If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict. If there are multiple answers, you can print any of them.

NoteIn the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed  - 1 in the first section, but notice that we printed this tree in the second section.In the second sample:In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this:  In the second tree, the algorithm will find an answer with 3 nodes which is correct:


You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.

The first line contains two integers, n and m (1 ≤ n ≤ 3000, 1 ≤ m ≤ 3000) — the number of words in the professor's lecture and the number of words in each of these languages. The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once. The next line contains n space-separated strings c1, c2, ..., cn — the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1, a2, ... am}. All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.

Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.

4 3
codeforces codesecrof
contest round
letter message
codeforces contest letter contest

5 3
joll wuqrd
euzf un
hbnyiyc rsoqqveh
hbnyiyc joll joll euzf joll

codeforces round letter round
hbnyiyc joll joll un joll

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));

	$mp = array();
	while ($b>0)
	{
list($c, $d) = explode(" ", trim(fgets(STDIN)));
		if(strlen($c)>strlen($d))
			$mp[$c]=$d;
		else
			$mp[$c]=$c;
	$b--;}

$qw = explode(" ", trim(fgets(STDIN)));
	for ($i=0;$i<$a;$i++)
	{
		if ($i != $a-1)
		echo $mp[$qw[$i]]." ";
else echo $mp[$qw[$i]].PHP_EOL;
	}

?>

<?php
$string=explode(" ", readline());
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo1 = array();
$arreglo2 = array();
for($i = 0; $i <$palabras+1; $i++){
    if($i == $palabras){
        $ultimas= explode(" ",readline() );
    }else{
 list($a,$b) = explode(" ",readline());
    $arreglo1[$a] = $b;
    $arreglo2[$b] = $a;
    }
}

$resultado = [];
foreach($ultimas as $ultima){
        if(strlen($ultima) <= strlen($arreglo1[$ultima])){
            $resultado[] = $ultima;
        }else{
            $resultado[] = $arreglo1[$ultima];
        }
}
echo implode(" ",$resultado);

<?php

$head_str = readline();

$head_info = explode(' ', $head_str);
$lection_size = $head_info[0];
$voc_size = $head_info[1];

$voc = [];

for($a = 0;$a < $voc_size; $a++){

    $voc_str = trim(readline());
    $data = explode(' ', $voc_str);

    if(strlen($data[0]) > strlen($data[1])){
        $short_sting = $data[1];
    }
    else{
        $short_sting = $data[0];
    }

    $voc[$data[0]] = $short_sting;

}

$lection = readline();

$lection_array = explode(' ', $lection);
$new_lect = [];
for($a = 0;$a < $lection_size; $a++){
    $new_lect[] = $voc[$lection_array[$a]];
}

$return = implode(' ', $new_lect);

print_r($return);

return 0;

?>

<?php
/*
 * Secdra @2020
 */

fscanf(STDIN, "%d %d", $n, $m);
$dic = [];
for ($i = 0; $i < $m; $i++) {
    fscanf(STDIN, "%s %s", $a, $b);
    $dic[$a] = $b;
}

$sentence = explode(' ', trim(fgets(STDIN)));
foreach ($sentence as $word) {
    printf("%s ", (strlen($word) <= strlen($dic[$word])) ? $word : $dic[$word]);
}

<?php

$line = array_map('intval',explode(' ', trim(fgets(STDIN))));
$n = $line[0];
$m = $line[1];
$trans = [];
for ($i = 0; $i < $m; $i++) {
	$couple = explode(' ', trim(fgets(STDIN)));
	if (strlen($couple[0]) <= strlen($couple[1])) {
		$key = $couple[0];
		$val = $couple[0];
	}
	else {
		$key = $couple[0];
		$val = $couple[1];
	}
	$trans[$key] = $val;
}

for ($i = 0; $i < $n; $i++) {
	$words = explode(' ', trim(fgets(STDIN)));
	foreach ($words as $word) {
		echo $trans[$word]." ";
	}
}

echo $res;

<?php
$numletter=trim(fgets(STDIN));
settype($numletter,'string');
$numletter=explode(' ',$numletter)[1];
$array=[];
$help1=[];
for ($i=0;$i<$numletter;$i++) {
$help=fgets(STDIN);
$help1=str_word_count($help,1);
$array[$help1[0]]=$help1[1];
}
 $result=null;
 $jomle=str_word_count(fgets(STDIN),1);
foreach ($jomle as $key => $kalame) {
     if(strlen($array[$kalame]) < strlen($kalame)){
        $jomle[$key]=$array[$kalame];
     }
}
echo join(' ',$jomle);

<?php
fscanf(STDIN,"%d %d",$n,$m);
for($i=0;$i<$m;$i++)
{
	$line[$i]=explode(" ",trim(fgets(STDIN)));
     if(strlen($line[$i][0])<=strlen($line[$i][1]))
     	 $str[$i]=$line[$i][0];
     	else
     		$str[$i]=$line[$i][1];

}
//print_r($str);
$text=explode(" ",trim(fgets(STDIN)));
//print_r($text);

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

    // echo "text=$text[$i]\n";
	if($text[$i]==$line[$j][0])
	{

         if($i==$n-1)
         	echo "$str[$j]";
         else
         	echo "$str[$j] ";
	}
}
}

<?php
list($m, $n) = explode(' ',fgets(STDIN));
$ab = [];
$ba = [];
for($i = 0; $i < $n; $i++){
    list($a,$b) = explode(' ',trim(fgets(STDIN)));
    $ab[$a] = $b;
    $ba[$b] = $a;
}
$words = explode(' ',trim(fgets(STDIN)));
$res = [];
foreach($words as $w){
    if(isset($ab[$w])){
        if(strlen($w) <= strlen($ab[$w])){
            $res[] = $w;
        }else{
            $res[] = $ab[$w];
        }
    }else{
        if(isset($ba[$w])){
            if(strlen($w) <= strlen($ba[$w])){
                $res[] = $w;
            }else{
                $res[] = $ba[$w];
            }
        }
    }
}
echo implode(' ',$res) . PHP_EOL;

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

$s = trim(fgets($f));
list($n,$m) = explode(" ",$s);

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

    if (strlen($b)<strlen($a)){
        $repl[$a] = $b;
    }
}

$s = trim(fgets($f));
$x = explode(" ",$s);
$y = array();
foreach($x as $item){
    if (isset($repl[$item])) $y[] = $repl[$item]; else $y[] = $item;
}

echo implode(" ",$y);

<?php
list($m, $n) = explode(" ",fgets(STDIN));
$idioma1 = array();
$idioma2 = array();
for($i = 0; $i < $n; $i++){
    list($a,$b) = explode(" ",trim(fgets(STDIN)));
    $idioma1[$a] = $b;
    $idioma2[$b] = $a;
    //echo "este es a: ".$a." este es b: ".$b." este es idioma1[a]: ". $idioma1[$a] . " este es idioma2[b]: " . $idioma2[$b];
}
//var_dump($idioma1);
//var_dump($idioma2);
$palabras = explode(" ",trim(fgets(STDIN)));
$resultado = [];
foreach($palabras as $palabra){
    if(isset($idioma1[$palabra])){
        if(strlen($palabra) <= strlen($idioma1[$palabra])){
            $resultado[] = $palabra;
        }else{
            $resultado[] = $idioma1[$palabra];
        }
    }elseif(isset($idioma2[$palabra])){
            if(strlen($palabra) <= strlen($idioma2[$palabra])){
                $resultado[] = $palabra;
            }else{
                $resultado[] = $idioma2[$palabra];
            }
        }
}
echo implode(" ",$resultado);

<?php

$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo1 = array();
$arreglo2 = array();
for($i = 0; $i < $numero+1; $i++){

    if($i == $numero-1){
        $palabras = explode(" ",readline() );
    }else{
 list($a,$b) = explode(" ",trim(fgets(STDIN)));
    $arreglo1[$a] = $b;
    $arreglo2[$b] = $a;
    }
}

$resultado = [];
foreach($palabras as $palabra){
        if(strlen($palabra) <= strlen($arreglo1[$palabra])){
            $resultado[] = $palabra;
        }else{
            $resultado[] = $arreglo1[$palabra];
        }
}
echo implode(" ",$resultado);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ",readline());
$impresion=[];
for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
     $aux2=$arreglo[$j];
    $porciones2=explode(" ",$aux2);
   // echo $arreglo[$j]."****". $porciones[$i]."\n" ;
    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
      if( strlen ( $porciones2[0])==strlen ($porciones[$i]) ){
 $impresion[]=$porciones2[0];
      }

       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
      if( strlen ( $porciones2[1])==strlen ($porciones[$i]) ){
 $impresion[]=$porciones2[1];
      }

         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
//echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ",readline());
$impresion=[];
for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) ){
     $aux2=$arreglo[$j];
    $porciones2=explode(" ",$aux2);
   // echo $arreglo[$j]."****". $porciones[$i]."\n" ;
    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
      $impresion[]=$porciones2[0];

       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
      $impresion[]=$porciones2[1];

         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);
$impresion=[];
for($i=0;$i< $numero;$i++){
 for($j=0;$j< $palabras;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
    $porciones2=explode(" ", $arreglo[$j]);

    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
        $impresion[]=$porciones2[1];
        // echo $porciones2[1]." ".$porciones[$i]."\n";
    }
    $porciones2[1]="";
    $porciones2[0]="";

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);
$impresion=[];

for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
    $porciones2=explode(" ", $arreglo[$j]);

    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
        $impresion[]=$porciones2[1];
         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ",readline());
$impresion=[];
for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
     $aux2=$arreglo[$j];
    $porciones2=explode(" ",$aux2);
   // echo $arreglo[$j]."****". $porciones[$i]."\n" ;
    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
      if( strlen ( $porciones2[0])==strlen ($porciones[$i]) ){
 $impresion[]=$porciones2[0];
      }

       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
      if( strlen ( $porciones2[1])==strlen ($porciones[$i]) ){
 $impresion[]=$porciones2[1];
      }

         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}
 $aux= $arreglo[$palabras];
$porciones=explode(" ",$aux);
$impresion=[];

for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
     $aux2=$arreglo[$j];
    $porciones2=explode(" ",$aux2);
 //echo $arreglo[$j]."****". $porciones[$i]."\n" ;
    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
        $impresion[]=$porciones2[1];
         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);
$impresion=[];

for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
    $porciones2=explode(" ", $arreglo[$j]);

    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
        $impresion[]=$porciones2[1];
         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }
    $porciones2[1]="";
    $porciones2[0]="";

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ",readline());
$impresion=[];
for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if($arreglo[$j] != $porciones[$i]){
     $aux2=$arreglo[$j];
    $porciones2=explode(" ",$aux2);
   // echo $arreglo[$j]."****". $porciones[$i]."\n" ;
    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
        $impresion[]=$porciones2[1];
         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
//echo implode(" ",$impresion);

<?php
$linea=fgets(STDIN);
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);
$string="";
for($i=0;$i< $numero;$i++){
 for($j=0;$j< $palabras;$j++){
  if(strpos($arreglo[$j], $porciones[$i] ) !== false){

    $porciones2=explode(" ", $arreglo[$j]);

     if( strlen ($porciones2[0])  == strlen ($porciones2[1]) )  {
        if($i==0){$string.=  $porciones2[0];}else{$string.= " ".$porciones2[0];}
    }elseif(strlen ($porciones2[0])  < strlen ($porciones2[1])){
       if($i==0){$string.=  $porciones2[0];}else{$string.= " ".$porciones2[0];}
    }else{
       if($i==0){$string.=  $porciones2[1];}else{$string.= " ".$porciones2[1];}
    }

   unset($porciones2);
  }

}

}
echo $string;

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ",readline());
$impresion=[];
for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
     $aux2=$arreglo[$j];
    $porciones2=explode(" ",$aux2);
   // echo $arreglo[$j]."****". $porciones[$i]."\n" ;
    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
      if( strlen ( $porciones2[0])==strlen ($porciones[$i]) || strlen ( $porciones2[1])==strlen ($porciones[$i]) ){
 $impresion[]=$porciones2[0];
      }

       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
      if( strlen ( $porciones2[1])==strlen ($porciones[$i])||strlen ( $porciones2[0])==strlen ($porciones[$i])  ){
 $impresion[]=$porciones2[1];
      }

         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=fgets(STDIN);
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);
$impresion=[];
$pos=0;
for($i=0;$i< $numero;$i++){
 for($j=0;$j< $palabras;$j++){
  if(strpos($arreglo[$j], $porciones[$i] ) !== false){

    $porciones2=explode(" ", $arreglo[$j]);

     if( strlen ($porciones2[0])  == strlen ($porciones2[1]) )  {
        $impresion[]=$porciones2[0];
    }elseif(strlen ($porciones2[0])  < strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
    }else{
        $impresion[]=$porciones2[1];
    }

   unset($porciones2);
  }

}

}
echo implode(" ",$impresion);

<?php
$linea=fgets(STDIN);
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);

for($i=0;$i< $numero;$i++){
 for($j=0;$j< $palabras;$j++){
  if(strpos($arreglo[$j], $porciones[$i] ) !== false){

    $porciones2=explode(" ", $arreglo[$j]);
     if( strlen ($porciones2[0])  == strlen ($porciones2[1]) )  {
        echo $porciones2[0];
    }elseif(strlen ($porciones2[0])  < strlen ($porciones2[1])){
      echo $porciones2[0];
    }else{
      echo $porciones2[1];
    }
    if($i!= $numero-1){
      echo " ";
    }

   unset($porciones2);
  }

}

}

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);
$impresion=[];
$pos=0;
for($i=0;$i< $numero;$i++){
 for($j=0;$j< $palabras;$j++){
  if(strpos($arreglo[$j], $porciones[$i] ) !== false){

    $porciones2=explode(" ", $arreglo[$j]);

     if( strlen ($porciones2[0])  == strlen ($porciones2[1]) )  {
        $impresion[]=$porciones2[0];
    }elseif(strlen ($porciones2[0])  < strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
    }else{
        $impresion[]=$porciones2[1];
    }

   unset($porciones2);
  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}
 $aux= $arreglo[$palabras];
$porciones=explode(" ",$aux);
$impresion=[];

for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
     $aux2=$arreglo[$j];
    $porciones2=explode(" ",$aux2);
 echo $arreglo[$j]."****". $porciones[$i]."\n" ;
    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
        $impresion[]=$porciones2[1];
         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);
$impresion=[];

for($i=0;$i< $palabras;$i++){
 for($j=0;$j< $numero;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
    $porciones2=explode(" ", $arreglo[$j]);

    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
        $impresion[]=$porciones2[1];
         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }
    $porciones2[1]="";
    $porciones2[0]="";

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ",readline());
$impresion=[];

for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
     $aux2=$arreglo[$j];
    $porciones2=explode(" ",$aux2);
 //echo $arreglo[$j]."****". $porciones[$i]."\n" ;
    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
        $impresion[]=$porciones2[1];
         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=fgets(STDIN);
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);

for($i=0;$i< $numero;$i++){
 for($j=0;$j< $palabras;$j++){
  if(strpos($arreglo[$j], $porciones[$i] ) !== false){

    $porciones2=explode(" ", $arreglo[$j]);
     if( strlen ($porciones2[0])  == strlen ($porciones2[1]) )  {
        echo $porciones2[0];
    }elseif(strlen ($porciones2[0])  < strlen ($porciones2[1])){
      echo $porciones2[0];
    }else{
      echo $porciones2[1];
    }
    echo " ";
   unset($porciones2);
  }

}

}

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);
$impresion=[];
for($i=0;$i< $numero;$i++){
 for($j=0;$j< $palabras;$j++){
   $porciones2=explode(" ", $arreglo[$j]);
  if(strpos($arreglo[$j],$porciones[$i]) !== false  &&( strlen ($porciones2[0])== strlen ($porciones[$i])  ||  strlen ($porciones2[1])== strlen ($porciones[$i])) ){

    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
        $impresion[]=$porciones2[1];
        // echo $porciones2[1]." ".$porciones[$i]."\n";
    }
    $porciones2[1]="";
    $porciones2[0]="";

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ",readline());
$impresion=[];
for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
     $aux2=$arreglo[$j];
    $porciones2=explode(" ",$aux2);
   // echo $arreglo[$j]."****". $porciones[$i]."\n" ;
    if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
      if( (strlen ( $porciones2[0])==strlen ($porciones[$i])) ||( strlen ( $porciones2[1])==strlen ($porciones[$i])) ){
 $impresion[]=$porciones2[0];
      }

       // $porciones2[0]." ".$porciones[$i]."\n";
    }else{
      if( (strlen ( $porciones2[1])==strlen ($porciones[$i]))||(strlen ( $porciones2[0])==strlen ($porciones[$i])  )){
 $impresion[]=$porciones2[1];
      }

         //echo $porciones2[1]." ".$porciones[$i]."\n";
    }

  }

}

}
echo implode(" ",$impresion);

<?php
$linea=fgets(STDIN);
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras+1;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ", $arreglo[$palabras]);
$impresion=[];
$pos=0;
for($i=0;$i< $numero;$i++){
 for($j=0;$j< $palabras;$j++){
  if(strpos($arreglo[$j], $porciones[$i] ) !== false){

    $porciones2=explode(" ", $arreglo[$j]);

     if( strlen ($porciones2[0])  == strlen ($porciones2[1]) )  {
        $impresion[]=$porciones2[0];
    }elseif(strlen ($porciones2[0])  < strlen ($porciones2[1])){
       $impresion[]=$porciones2[0];
    }else{
        $impresion[]=$porciones2[1];
    }

    $porciones2[0]="";
 $porciones2[1]="";

  }

}

}
echo implode(" ",$impresion);

<?php

$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo1 = array();
$arreglo2 = array();
for($i = 0; $i < $numero+1; $i++){
    list($a,$b) = explode(" ",trim(fgets(STDIN)));
    $arreglo1[$a] = $b;
    $arreglo2[$b] = $a;
    if($i == $numero-1){
        $palabras = explode(" ",readline() );
    }
}

$resultado = [];
foreach($palabras as $palabra){
        if(strlen($palabra) <= strlen($arreglo1[$palabra])){
            $resultado[] = $palabra;
        }else{
            $resultado[] = $arreglo1[$palabra];
        }
}
echo implode(" ",$resultado);

<?php
$linea=readline();
$string=explode(" ", $linea);
$numero= intval($string[0]);
$palabras= intval($string[1]);
$arreglo=array( $palabras+1);
for($i=0;$i< $palabras;$i++){
  $palabra=readline();
  $arreglo[$i]= $palabra;
}

$porciones=explode(" ",readline());
$impresion=[];
for($i=0;$i<$numero;$i++){
 for($j=0;$j< $palabras ;$j++){
  if(strpos($arreglo[$j],$porciones[$i]) !== false){
    $porciones2=explode(" ", $arreglo[$j]);
   if(strlen ($porciones2[0]) ==  strlen ($porciones[$i]) ||strlen ($porciones2[1]) ==  strlen ($porciones[$i]) ){
       if(strlen ($porciones2[0])  <= strlen ($porciones2[1])){
      $impresion[]=$porciones2[0];
    }else{
    $impresion[]=$porciones2[1];

    }
   }

  }

}

}
echo implode(" ",$impresion);

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

$s = trim(fgets($f));
list($n,$m) = explode(" ",$s);

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

    if (strlen($b)<strlen($a)){
        $repl[$a] = $b;
    }
}

$s = trim(fgets($f));
$s=$s." ";
foreach($repl as $k=>$item){
    $s = str_replace($k." ",$item." ",$s);
}

echo $s;

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

$s = trim(fgets($f));
list($n,$m) = explode(" ",$s);

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

    if (strlen($b)<strlen($a)){
        $repl[$a] = $b;
    }
}

$s = trim(fgets($f));
$s=" ".$s." ";
foreach($repl as $k=>$item){
    $s = str_replace(" ".$k." "," ".$item." ",$s);
}

echo trim($s);


You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α.  Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.

The first line contains three integers w, h, α (1 ≤ w, h ≤ 106; 0 ≤ α ≤ 180). Angle α is given in degrees.

In a single line print a real number — the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.

NoteThe second sample has been drawn on the picture above.


You are given a string $$$s$$$ consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of queries. Each of the next $$$t$$$ lines contains one string. The $$$i$$$-th line contains a string $$$s_i$$$ consisting only of lowercase Latin letter. It is guaranteed that the length of $$$s_i$$$ is from $$$1$$$ to $$$1000$$$ (inclusive).

Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: -1 if it is impossible to obtain a good string by rearranging the letters of $$$s_i$$$ and any good string which can be obtained from the given one (by rearranging the letters) otherwise.

NoteIn the first query we cannot rearrange letters to obtain a good string.Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".In the third query we can do nothing to obtain a good string.

<?php
$a = trim(fgets(STDIN));
for($x = 0; $x < $a; $x++)
{
     $b = str_split(trim(fgets(STDIN)));
     if(count(array_unique($b)) == 1)
     {
          print "-1\n";
     }
     else
     {
          sort($b);
          print implode($b) . "\n";
     }
}
?>

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

for ($i = 0; $i < $number ; $i++) {
	$string = trim(fgets(STDIN));
	$array = str_split($string);
	sort($array);
	$a = array_unique($array);
	if(count($a) == 1){
		echo "-1\n";
		continue;
	}
	echo implode('',$array)."\n";
}

<?php
$t = readline();

for ($i = 0; $i < $t; $i++){
    $str = readline();
    $arr = str_split($str);
    sort($arr);
    $first = $arr[0];
    $tot = count($arr);
    $last = $arr[$tot - 1];
    if($first == $last) {
        echo "-1\n";
    }
    else {
        $len = count($arr);
        for($j = 0 ; $j < $len ; $j++) {
            echo $arr[$j];
        }
        print "\n";
    }
}

<?php
$t = readline();
for ($i = 0; $i < $t; $i++){
    $str = readline();
    $arr = str_split($str);
    sort($arr);
    $first = reset($arr);
    $last = end($arr);
    print_r(($first == $last ? -1 : implode('',$arr)). PHP_EOL);
}

<?php
$t = trim(fgets(STDIN));
for ($i = 0; $i < $t; $i++){
    $str = trim(fgets(STDIN));
    $arr = str_split($str);
    sort($arr);
    $first = reset($arr);
    $last = end($arr);
    print_r(($first == $last ? -1 : implode('',$arr)). PHP_EOL);
}

<?php
fscanf(STDIN, "%u",$N);
$resultArr = [];
for ($i = 0; $i < $N; $i++) {
    fscanf(STDIN, "%s", $str);
    $arr1 = str_split($str);
    sort($arr1);
    if (count(array_unique($arr1)) == 1) {
        $resultArr[] = -1;
    } else $resultArr[] = implode('', $arr1);
}
foreach($resultArr as $v) {
    echo $v . PHP_EOL;
}

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

for ($i = 0; $i < $number ; $i++) {
	$string = trim(fgets(STDIN));
		for ($j = 0; $j < strlen($string); $j++) {
				if($string[0] != $string[$j]){
					echo $string."\n";
					$a = true;
					break;
				}
			}
			if(!isset($a)){
				echo "-1\n";
			}
}

<?php
$t = readline();

for ($i = 0; $i < $t; $i++){
    $str = readline();
    $arr = str_split($str);
    sort($arr);
    $first = $arr[0];
    $tot = count($arr);
    $last = $arr[$tot - 1];
    if($first == $last) {
        echo '-1';
    }
    else {
        $len = count($arr);
        for($j = 0 ; $j < $len ; $j++) {
            echo $arr[$j];
        }
    }
}

<?php
$t = readline();

for ($i = 0; $i < $t; $i++){
    $str = readline();
    $arr = str_split($str);
    sort($arr);
    $first = $arr[0];
    $tot = count($arr);
    $last = $arr[$tot - 1];
    if($first == $last) {
        echo '-1\n';
    }
    else {
        $len = count($arr);
        for($j = 0 ; $j < $len ; $j++) {
            echo $arr[$j];
        }
        echo '\n';
    }
}


A flowerbed has many flowers and two fountains.You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains.You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12 + r22 is minimum possible. Find this minimum value.

The first line of the input contains integers n, x1, y1, x2, y2 (1 ≤ n ≤ 2000,  - 107 ≤ x1, y1, x2, y2 ≤ 107) — the number of flowers, the coordinates of the first and the second fountain. Next follow n lines. The i-th of these lines contains integers xi and yi ( - 107 ≤ xi, yi ≤ 107) — the coordinates of the i-th flower. It is guaranteed that all n + 2 points in the input are distinct.

Print the minimum possible value r12 + r22. Note, that in this problem optimal answer is always integer.

NoteThe first sample is (r12 = 5, r22 = 1):  The second sample is (r12 = 1, r22 = 32):

<?php
/**
 * Author: 七柳先森
 * Date: 2016/1/25  9:09
 */
while( fscanf(STDIN,"%f %f %f %f %f",$n,$x1,$y1,$x2,$y2) ){
    $dist = array();
    for($i = 0 ; $i < $n ; $i++){
        fscanf(STDIN,"%f %f",$fwx,$fwy);
        array_push($dist,[ pow($fwx-$x1,2)+pow($fwy-$y1,2) , pow($fwx-$x2,2)+pow($fwy-$y2,2) ]);
    }
    $result = 8e18;
    //思路，先确定第一个喷泉的范围，再选第二个。

    $dist[] = [0,0];
    for($i = 0 ; $i < $n+1 ; $i++){
        $r1 = $dist[$i][0];
        $r2 = 0;
        for($j = 0 ; $j < $n ; $j++){
            //当其它点到第一个喷泉的距离大于第一个的时候，我们需要使用第二个。
            //保存到第二个喷泉的最大距离。
            if($dist[$j][0] > $r1) {
                $r2 = max($r2, $dist[$j][1]);
            }
        }
        $result = min($result,$r1+$r2);
    }
    fprintf(STDOUT,"%.0f",$result);
    exit();
}

<?php
list($a, $b, $c, $d, $e) = explode(" ", trim(fgets(STDIN)));
$f = array();
$g = array();
for($x = 0; $x < $a; $x++)
{
     list($h, $i) = explode(" ", trim(fgets(STDIN)));
     $j = bcpow(bcsqrt(bcadd(bcpow(bcsub($h, $b), 2), bcpow(bcsub($i, $c), 2))), 2);
     $f[$x] = $j;
     $k = bcpow(bcsqrt(bcadd(bcpow(bcsub($h, $d), 2), bcpow(bcsub($i, $e), 2))), 2);
     $g[$x] = $k;
}
$l = max($f);
$m = max($g);
$n = array($l, $m);
$o = 2;
array_unshift($f, " ");
unset($f[0]);
array_unshift($g, " ");
unset($g[0]);
$p = 0;
for($x = 1; $x <= $a; $x++)
{
     $r = max($f);
     $s = array_search($r, $f);
     $p = max($p, $g[$s]);
     unset($f[$s]);
     $n[$o] = max($f) + $p;
     $o++;
}
print min($n);
?>

<?php
/**
 * Author: 七柳先森
 * Date: 2016/1/25  9:09
 */
//从这个例子中我们也可以看到自己的php版本是32位的。
//如果使用浮点数，会形成误差。
function mypow($d){
    $d = (string)$d;
    return bcpow($d,"2");
}
while( fscanf(STDIN,"%d %d %d %d %d",$n,$x1,$y1,$x2,$y2) ){
    $dist = array();
    for($i = 0 ; $i < $n ; $i++){
        fscanf(STDIN,"%d %d",$fwx,$fwy);
        array_push($dist,[ bcadd(mypow($fwx-$x1),mypow($fwy-$y1)) , bcadd(mypow($fwx-$x2),mypow($fwy-$y2)) ]);
    }
    $result = "9000000000000000000000";
    //思路，先确定第一个喷泉的范围，再选第二个。

    $dist[] = ["0","0"];
    for($i = 0 ; $i < $n+1 ; $i++){
        $r1 = $dist[$i][0];
        $r2 = "0";
        for($j = 0 ; $j < $n ; $j++){
            //当其它点到第一个喷泉的距离大于第一个的时候，我们需要使用第二个。
            //保存到第二个喷泉的最大距离。
            if(strcmp($dist[$j][0] , $r1) > 0) {
                if(strcmp($dist[$j][1],$r2) > 0){
                    $r2 = $dist[$j][1];
                }

            }
        }
      //  var_dump($r1);
       // var_dump($r2);
        if(strcmp($result,bcadd($r1,$r2))) {
            $result = bcadd($r1, $r2);
        }
    }
    fprintf(STDOUT,"%s",$result);

    exit();
}

<?php
/**
 * Author: 七柳先森
 * Date: 2016/1/25  9:09
 */
//从这个例子中我们也可以看到自己的php版本是32位的。
//如果使用浮点数，会形成误差。
function mypow($d){
    $d = (string)$d;
    return bcpow($d,"2");
}
while( fscanf(STDIN,"%d %d %d %d %d",$n,$x1,$y1,$x2,$y2) ){
    $dist = array();
    for($i = 0 ; $i < $n ; $i++){
        fscanf(STDIN,"%d %d",$fwx,$fwy);
        array_push($dist,[ bcadd(mypow($fwx-$x1),mypow($fwy-$y1)) , bcadd(mypow($fwx-$x2),mypow($fwy-$y2)) ]);
    }
    $result = "9000000000000000000000";
    //思路，先确定第一个喷泉的范围，再选第二个。

    $dist[] = ["0","0"];
    for($i = 0 ; $i < $n+1 ; $i++){
        $r1 = $dist[$i][0];
        $r2 = "0";
        for($j = 0 ; $j < $n ; $j++){
            //当其它点到第一个喷泉的距离大于第一个的时候，我们需要使用第二个。
            //保存到第二个喷泉的最大距离。
            if(strcmp($dist[$j][0] , $r1) > 0) {
                if(strcmp($dist[$j][1],$r2) > 0){
                    $r2 = $dist[$j][1];
                }

            }
        }
      //  var_dump($r1);
       // var_dump($r2);
        if(strcmp($result,bcadd($r1,$r2)) > 0) {
            $result = bcadd($r1, $r2);
        }
    }
    fprintf(STDOUT,"%s",$result);

    exit();
}

<?php
/**
 * Author: 七柳先森
 * Date: 2016/1/25  9:09
 */
while( fscanf(STDIN,"%f %f %f %f %f",$n,$x1,$y1,$x2,$y2) ){
    $dist = array();
    for($i = 0 ; $i < $n ; $i++){
        fscanf(STDIN,"%f %f",$fwx,$fwy);
        array_push($dist,[ pow($fwx-$x1,2)+pow($fwy-$y1,2) , pow($fwx-$x2,2)+pow($fwy-$y2,2) ]);
    }
    $result = 8e18;
    //思路，先确定第一个喷泉的范围，再选第二个。
    for($i = 0 ; $i < $n ; $i++){
        $r1 = $dist[$i][0];
        $r2 = 0;
        for($j = 0 ; $j < $n ; $j++){
            //当其它点到第一个喷泉的距离大于第一个的时候，我们需要使用第二个。
            //保存到第二个喷泉的最大距离。
            if($dist[$j][0] > $r1) {
                $r2 = max($r2, $dist[$j][1]);
            }
        }
        $result = min($result,$r1+$r2);
    }
    fprintf(STDOUT,"%.0f",$result);
    exit();
}


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

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

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


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

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

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

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

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

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


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

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

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

9
arrayhead
5
arya
harry
ray
r
areahydra

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

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


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

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

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

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


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

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

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


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

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

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

6

5 r

rggry

1 g

g

3 r

rrg

5 y

yrrgy

7 r

rgrgyrg

9 y

rrrgyyygy

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

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

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


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

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

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

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

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

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

}


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

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

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

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

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

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

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

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

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

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

        $map_b[$offset] ++ ;

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

    echo $ans . "\n" ;
?>

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

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

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

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

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

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

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

    echo $ans . "\n" ;
?>


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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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

echo $res;

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


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

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

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

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

<?php

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

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

$sumOfSegments = array_sum($encoding);

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


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

<?php

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

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


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

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

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

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

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

<?php

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

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


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

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

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

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

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