There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that   starts in the upper left cell of the matrix;  each following cell is to the right or down from the current cell;  the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.

The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).

In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.

<?php

/**
 * http://codeforces.com/problemset/problem/2/B
 *
 * Задана квадратная матрица n × n, состоящая из неотрицательных целых чисел.
 * Вам надо найти такой путь на ней, который
 * начинается в левой верхней ячейке матрицы;
 * каждой следующей ячейкой имеет правую или нижнюю от текущей;
 * заканчивается в правой нижней клетке.
 *
 * Кроме того, если перемножить все числа вдоль пути и посмотреть на
 * получившиеся произведение, то это число должно быть как можно менее «круглым».
 * Иными словами оно должно заканчиваться на наименьшее возможное количество нулей.
 */

define('DEBUG', 0);

function doLog($log) {
	if (DEBUG) {
		echo "[" . microtime(true) ."] " . $log . "\n";
	}
}

function dumpArray($a, $n) {
	if (DEBUG) {
		for ($i = 0; $i<$n; $i++) {
			for ($j = 0; $j<$n; $j++) {
				echo "\t{$a[$i][$j]}";
			}
			echo "\n";
		}
		echo "\n";
	}
}

$numbersRow2 = [];
$numbersRow5 = [];
$directionsArray = [];

$n = trim(fgets(STDIN));

$time = microtime(true);

//$numString = explode(' ' , trim(fgets(STDIN)));
//$format = str_repeat('%d', $n);
$wasZero = [];
for ($i = 0; $i<$n; $i++) {
	$directionsArray[$i] = str_repeat(' ', $n);
	$numString = explode(' ' , trim(fgets(STDIN)));
	//$numString = sscanf(trim(fgets(STDIN)), $format);
	for ($j = 0; $j<$n; $j++) {
		$num = $numString[$j];
		$n2 = $n5 = 0;

		if ($num==0) {
			$n2 = $n5 = 0;
			$wasZero = [$i, $j];
		} else {
			while ($num && (($num & 1) == 0)) {
				$n2++;
				$num>>=1;
			}

			while ($num && ($num%5 == 0)) {
				$n5++;
				$num /= 5;
			}
		}

		if ($j>0) {
			//$njp = $numbersRow[$j-1];
			$njp5 = $numbersRow5[$j-1];
			$njp2 = $numbersRow2[$j-1];
		}
		$direction = 0;

		if ($i) {
			//$nj = $numbersRow[$j];
			$nj5 = $numbersRow5[$j];
			$nj2 = $numbersRow2[$j];
			if (!$j) {
				$direction = 3;
				$n5 += $nj5;
				$n2 += $nj2;
			} else {
				if ($njp5 <= $nj5) {
					$n5 += $njp5;
				} else {
					$n5 += $nj5;
					$direction = 1;
				}

				if ($njp2 <= $nj2) {
					$n2 += $njp2;
				} else {
					$n2 += $nj2;
					$direction += 2;
				}

			}
		}
		else {
			if ($j) {
				$n5 += $njp5;
				$n2 += $njp2;
			} else {
				$numbersRow2[$j] = 0;
				$numbersRow5[$j] = 0;
			}
		}
		$numbersRow2[$j] = $n2;
		$numbersRow5[$j] = $n5;
		$directionsArray[$i][$j] = chr($direction);
	}
}

$time2 = microtime(true);
//echo "first part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

$min2 = $numbersRow2[$n-1];
$min5 = $numbersRow5[$n-1];

function findMinPath(&$a, $i, $j, $bit) {
	if ($i==0 && $j==0) {
		return '';
	} elseif ($i==0) {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	} elseif ($j==0) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} elseif (ord($a[$i][$j]) & $bit) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} else {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	}
}

$min = min($min2, $min5);

// учесть вариант когда в таблице есть нуль (т.е. произведение по этому пути будет 0),
// но существует путь совсем без нулей
if ($min>1 && $wasZero) {
	$min = 1;
	$path = str_repeat('R', $wasZero[1]) . str_repeat('D', $n-1) . str_repeat('R', $n-1 - $wasZero[1]);
} else {
	$path = '';
	if ($min == $min2) {
		$path = findMinPath($directionsArray, $n-1, $n-1, 2);
	} else {
		$path = findMinPath($directionsArray, $n-1, $n-1, 1);
	}
}

$time2 = microtime(true);
//echo "second part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

echo $min . PHP_EOL . $path;

<?php

/**
 * http://codeforces.com/problemset/problem/2/B
 *
 * Задана квадратная матрица n × n, состоящая из неотрицательных целых чисел.
 * Вам надо найти такой путь на ней, который
 * начинается в левой верхней ячейке матрицы;
 * каждой следующей ячейкой имеет правую или нижнюю от текущей;
 * заканчивается в правой нижней клетке.
 *
 * Кроме того, если перемножить все числа вдоль пути и посмотреть на
 * получившиеся произведение, то это число должно быть как можно менее «круглым».
 * Иными словами оно должно заканчиваться на наименьшее возможное количество нулей.
 */

define('DEBUG', 0);

function doLog($log) {
	if (DEBUG) {
		echo "[" . microtime(true) ."] " . $log . "\n";
	}
}

function dumpArray($a, $n) {
	if (DEBUG) {
		for ($i = 0; $i<$n; $i++) {
			for ($j = 0; $j<$n; $j++) {
				echo "\t{$a[$i][$j]}";
			}
			echo "\n";
		}
		echo "\n";
	}
}

$numbersRow = [];
$directionsArray = [];

$n = trim(fgets(STDIN));

$time = microtime(true);

//$numString = explode(' ' , trim(fgets(STDIN)));
//$format = str_repeat('%d', $n);
for ($i = 0; $i<$n; $i++) {
	$directionsArray[$i] = str_repeat(' ', $n);
	$numString = explode(' ' , trim(fgets(STDIN)));
	//$numString = sscanf(trim(fgets(STDIN)), $format);
	for ($j = 0; $j<$n; $j++) {
		$num = $numString[$j];
		$n2 = $n5 = 0;

		while ($num && ($num & 1) == 0) {
			$n2++;
			$num>>=1;
		}

		while ($num && $num%5 == 0) {
			$n5++;
			$num /= 5;
		}

		if ($j>0) {
			$njp = $numbersRow[$j-1];
			$njp5 = ($njp >> 15);
			$njp2 = ($njp & (1<<15)-1);
		}
		$direction = 0;

		if ($i) {
			$nj = $numbersRow[$j];
			$nj5 = ($nj >> 15);
			$nj2 = ($nj & (1<<15)-1);
			if (!$j) {
				$direction = 3;
				$n5 += $nj5;
				$n2 += $nj2;
			} else {
				if ($njp5 <= $nj5) {
					$n5 += $njp5;
				} else {
					$n5 += $nj5;
					$direction = 1;
				}

				if ($njp2 <= $nj2) {
					$n2 += $njp2;
				} else {
					$n2 += $nj2;
					$direction += 2;
				}

			}
		}
		else {
			if ($j) {
				$n5 += $njp5;
				$n2 += $njp2;
			} else {
				$numbersRow[$j] = 0;
			}
		}
		$numbersRow[$j] = ($n5<<15) + $n2;
		$directionsArray[$i][$j] = chr($direction);
	}
}

$time2 = microtime(true);
//echo "first part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

$min2 = ($numbersRow[$n-1] & (1<<15)-1);
$min5 = ($numbersRow[$n-1]>>15);

function findMinPath(&$a, $i, $j, $bit) {
	if ($i==0 && $j==0) {
		return '';
	} elseif ($i==0) {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	} elseif ($j==0) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} elseif (ord($a[$i][$j]) & $bit) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} else {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	}
}

$min = min($min2, $min5);
$path = '';
if ($min == $min2) {
	$path = findMinPath($directionsArray, $n-1, $n-1, 2);
} else {
	$path = findMinPath($directionsArray, $n-1, $n-1, 1);
}

$time2 = microtime(true);
//echo "second part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

echo $min . PHP_EOL . $path;

<?php

/**
 * http://codeforces.com/problemset/problem/2/B
 *
 * Задана квадратная матрица n × n, состоящая из неотрицательных целых чисел.
 * Вам надо найти такой путь на ней, который
 * начинается в левой верхней ячейке матрицы;
 * каждой следующей ячейкой имеет правую или нижнюю от текущей;
 * заканчивается в правой нижней клетке.
 *
 * Кроме того, если перемножить все числа вдоль пути и посмотреть на
 * получившиеся произведение, то это число должно быть как можно менее «круглым».
 * Иными словами оно должно заканчиваться на наименьшее возможное количество нулей.
 */

define('DEBUG', 0);

function doLog($log) {
	if (DEBUG) {
		echo "[" . microtime(true) ."] " . $log . "\n";
	}
}

function dumpArray($a, $n) {
	if (DEBUG) {
		for ($i = 0; $i<$n; $i++) {
			for ($j = 0; $j<$n; $j++) {
				echo "\t{$a[$i][$j]}";
			}
			echo "\n";
		}
		echo "\n";
	}
}

$numbersRow = [];
$directionsArray = [];

$n = trim(fgets(STDIN));

$time = microtime(true);

//$numString = explode(' ' , trim(fgets(STDIN)));
//$format = str_repeat('%d', $n);
for ($i = 0; $i<$n; $i++) {
	$directionsArray[$i] = str_repeat(' ', $n);
	$numString = explode(' ' , trim(fgets(STDIN)));
	//$numString = sscanf(trim(fgets(STDIN)), $format);
	for ($j = 0; $j<$n; $j++) {
		$num = $numString[$j];
		$n2 = $n5 = 0;

		while ($num && (($num & 1) == 0)) {
			$n2++;
			$num>>=1;
		}

		while ($num && ($num%5 == 0)) {
			$n5++;
			$num /= 5;
		}

		if ($j>0) {
			$njp = $numbersRow[$j-1];
			$njp5 = ($njp >> 15);
			$njp2 = ($njp & (1<<15)-1);
		}
		$direction = 0;

		if ($i) {
			$nj = $numbersRow[$j];
			$nj5 = ($nj >> 15);
			$nj2 = ($nj & (1<<15)-1);
			if (!$j) {
				$direction = 3;
				$n5 += $nj5;
				$n2 += $nj2;
			} else {
				if ($njp5 <= $nj5) {
					$n5 += $njp5;
				} else {
					$n5 += $nj5;
					$direction = 1;
				}

				if ($njp2 <= $nj2) {
					$n2 += $njp2;
				} else {
					$n2 += $nj2;
					$direction += 2;
				}

			}
		}
		else {
			if ($j) {
				$n5 += $njp5;
				$n2 += $njp2;
			} else {
				$numbersRow[$j] = 0;
			}
		}
		$numbersRow[$j] = ($n5<<15) + $n2;
		$directionsArray[$i][$j] = chr($direction);
	}
}

$time2 = microtime(true);
//echo "first part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

$min2 = ($numbersRow[$n-1] & (1<<15)-1);
$min5 = ($numbersRow[$n-1]>>15);

function findMinPath(&$a, $i, $j, $bit) {
	if ($i==0 && $j==0) {
		return '';
	} elseif ($i==0) {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	} elseif ($j==0) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} elseif (ord($a[$i][$j]) & $bit) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} else {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	}
}

$min = min($min2, $min5);
$path = '';
if ($min == $min2) {
	$path = findMinPath($directionsArray, $n-1, $n-1, 2);
} else {
	$path = findMinPath($directionsArray, $n-1, $n-1, 1);
}

$time2 = microtime(true);
//echo "second part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

echo $min . PHP_EOL . $path;

<?php

/**
 * http://codeforces.com/problemset/problem/2/B
 *
 * Задана квадратная матрица n × n, состоящая из неотрицательных целых чисел.
 * Вам надо найти такой путь на ней, который
 * начинается в левой верхней ячейке матрицы;
 * каждой следующей ячейкой имеет правую или нижнюю от текущей;
 * заканчивается в правой нижней клетке.
 *
 * Кроме того, если перемножить все числа вдоль пути и посмотреть на
 * получившиеся произведение, то это число должно быть как можно менее «круглым».
 * Иными словами оно должно заканчиваться на наименьшее возможное количество нулей.
 */

define('DEBUG', 0);

function doLog($log) {
	if (DEBUG) {
		echo "[" . microtime(true) ."] " . $log . "\n";
	}
}

function dumpArray($a, $n) {
	if (DEBUG) {
		for ($i = 0; $i<$n; $i++) {
			for ($j = 0; $j<$n; $j++) {
				echo "\t{$a[$i][$j]}";
			}
			echo "\n";
		}
		echo "\n";
	}
}

$numbersRow2 = [];
$numbersRow5 = [];
$directionsArray = [];

$n = trim(fgets(STDIN));

$time = microtime(true);

//$numString = explode(' ' , trim(fgets(STDIN)));
//$format = str_repeat('%d', $n);
for ($i = 0; $i<$n; $i++) {
	$directionsArray[$i] = str_repeat(' ', $n);
	$numString = explode(' ' , trim(fgets(STDIN)));
	//$numString = sscanf(trim(fgets(STDIN)), $format);
	for ($j = 0; $j<$n; $j++) {
		$num = $numString[$j];
		$n2 = $n5 = 0;

		while ($num && (($num & 1) == 0)) {
			$n2++;
			$num>>=1;
		}

		while ($num && ($num%5 == 0)) {
			$n5++;
			$num /= 5;
		}

		if ($j>0) {
			//$njp = $numbersRow[$j-1];
			$njp5 = $numbersRow5[$j-1];
			$njp2 = $numbersRow2[$j-1];
		}
		$direction = 0;

		if ($i) {
			//$nj = $numbersRow[$j];
			$nj5 = $numbersRow5[$j];
			$nj2 = $numbersRow2[$j];
			if (!$j) {
				$direction = 3;
				$n5 += $nj5;
				$n2 += $nj2;
			} else {
				if ($njp5 <= $nj5) {
					$n5 += $njp5;
				} else {
					$n5 += $nj5;
					$direction = 1;
				}

				if ($njp2 <= $nj2) {
					$n2 += $njp2;
				} else {
					$n2 += $nj2;
					$direction += 2;
				}

			}
		}
		else {
			if ($j) {
				$n5 += $njp5;
				$n2 += $njp2;
			} else {
				$numbersRow2[$j] = 0;
				$numbersRow5[$j] = 0;
			}
		}
		$numbersRow2[$j] = $n2;
		$numbersRow5[$j] = $n5;
		$directionsArray[$i][$j] = chr($direction);
	}
}

$time2 = microtime(true);
//echo "first part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

$min2 = $numbersRow2[$n-1];
$min5 = $numbersRow5[$n-1];

function findMinPath(&$a, $i, $j, $bit) {
	if ($i==0 && $j==0) {
		return '';
	} elseif ($i==0) {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	} elseif ($j==0) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} elseif (ord($a[$i][$j]) & $bit) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} else {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	}
}

$min = min($min2, $min5);
$path = '';
if ($min == $min2) {
	$path = findMinPath($directionsArray, $n-1, $n-1, 2);
} else {
	$path = findMinPath($directionsArray, $n-1, $n-1, 1);
}

$time2 = microtime(true);
//echo "second part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

echo $min . PHP_EOL . $path;

<?php

/**
 * http://codeforces.com/problemset/problem/2/B
 *
 * Задана квадратная матрица n × n, состоящая из неотрицательных целых чисел.
 * Вам надо найти такой путь на ней, который
 * начинается в левой верхней ячейке матрицы;
 * каждой следующей ячейкой имеет правую или нижнюю от текущей;
 * заканчивается в правой нижней клетке.
 *
 * Кроме того, если перемножить все числа вдоль пути и посмотреть на
 * получившиеся произведение, то это число должно быть как можно менее «круглым».
 * Иными словами оно должно заканчиваться на наименьшее возможное количество нулей.
 */

define('DEBUG', 0);

function doLog($log) {
	if (DEBUG) {
		echo "[" . microtime(true) ."] " . $log . "\n";
	}
}

function dumpArray($a, $n) {
	if (DEBUG) {
		for ($i = 0; $i<$n; $i++) {
			for ($j = 0; $j<$n; $j++) {
				echo "\t{$a[$i][$j]}";
			}
			echo "\n";
		}
		echo "\n";
	}
}

$numbersRow = [];
$directionsArray = [];

$n = trim(fgets(STDIN));

$time = microtime(true);

//$numString = explode(' ' , trim(fgets(STDIN)));
//$format = str_repeat('%d', $n);
for ($i = 0; $i<$n; $i++) {
	$directionsArray[$i] = str_repeat(' ', $n);
	$numString = explode(' ' , trim(fgets(STDIN)));
	//$numString = sscanf(trim(fgets(STDIN)), $format);
	for ($j = 0; $j<$n; $j++) {
		$num = $numString[$j];
		$n2 = $n5 = 0;

		while ($num && (($num & 1) == 0)) {
			$n2++;
			$num>>=1;
		}

		while ($num && ($num%5 == 0)) {
			$n5++;
			$num /= 5;
		}

		if ($j>0) {
			$njp = $numbersRow[$j-1];
			$njp5 = ($njp >> 31);
			$njp2 = ($njp & (1<<31)-1);
		}
		$direction = 0;

		if ($i) {
			$nj = $numbersRow[$j];
			$nj5 = ($nj >> 31);
			$nj2 = ($nj & (1<<31)-1);
			if (!$j) {
				$direction = 3;
				$n5 += $nj5;
				$n2 += $nj2;
			} else {
				if ($njp5 <= $nj5) {
					$n5 += $njp5;
				} else {
					$n5 += $nj5;
					$direction = 1;
				}

				if ($njp2 <= $nj2) {
					$n2 += $njp2;
				} else {
					$n2 += $nj2;
					$direction += 2;
				}

			}
		}
		else {
			if ($j) {
				$n5 += $njp5;
				$n2 += $njp2;
			} else {
				$numbersRow[$j] = 0;
			}
		}
		$numbersRow[$j] = ($n5<<31) + $n2;
		$directionsArray[$i][$j] = chr($direction);
	}
}

$time2 = microtime(true);
//echo "first part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

$min2 = ($numbersRow[$n-1] & (1<<31)-1);
$min5 = ($numbersRow[$n-1]>>31);

function findMinPath(&$a, $i, $j, $bit) {
	if ($i==0 && $j==0) {
		return '';
	} elseif ($i==0) {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	} elseif ($j==0) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} elseif (ord($a[$i][$j]) & $bit) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} else {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	}
}

$min = min($min2, $min5);
$path = '';
if ($min == $min2) {
	$path = findMinPath($directionsArray, $n-1, $n-1, 2);
} else {
	$path = findMinPath($directionsArray, $n-1, $n-1, 1);
}

$time2 = microtime(true);
//echo "second part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

echo $min . PHP_EOL . $path;

<?php

/**
 * http://codeforces.com/problemset/problem/2/B
 *
 * Задана квадратная матрица n × n, состоящая из неотрицательных целых чисел.
 * Вам надо найти такой путь на ней, который
 * начинается в левой верхней ячейке матрицы;
 * каждой следующей ячейкой имеет правую или нижнюю от текущей;
 * заканчивается в правой нижней клетке.
 *
 * Кроме того, если перемножить все числа вдоль пути и посмотреть на
 * получившиеся произведение, то это число должно быть как можно менее «круглым».
 * Иными словами оно должно заканчиваться на наименьшее возможное количество нулей.
 */

define('DEBUG', 0);

function doLog($log) {
	if (DEBUG) {
		echo "[" . microtime(true) ."] " . $log . "\n";
	}
}

function dumpArray($a, $n) {
	if (DEBUG) {
		for ($i = 0; $i<$n; $i++) {
			for ($j = 0; $j<$n; $j++) {
				echo "\t{$a[$i][$j]}";
			}
			echo "\n";
		}
		echo "\n";
	}
}

$numbersRow = [];
$directionsArray = [];

$n = trim(fgets(STDIN));

$time = microtime(true);

//$numString = explode(' ' , trim(fgets(STDIN)));
//$format = str_repeat('%d', $n);
for ($i = 0; $i<$n; $i++) {
	$directionsArray[$i] = str_repeat(' ', $n);
	$numString = explode(' ' , trim(fgets(STDIN)));
	//$numString = sscanf(trim(fgets(STDIN)), $format);
	for ($j = 0; $j<$n; $j++) {
		$num = $numString[$j];
		$n2 = $n5 = 0;

		while ($num && (($num & 1) == 0)) {
			$n2++;
			$num>>=1;
		}

		while ($num && ($num%5 == 0)) {
			$n5++;
			$num /= 5;
		}

		if ($j>0) {
			$njp = $numbersRow[$j-1];
			$njp5 = ($njp >> 20);
			$njp2 = ($njp & (1<<20)-1);
		}
		$direction = 0;

		if ($i) {
			$nj = $numbersRow[$j];
			$nj5 = ($nj >> 20);
			$nj2 = ($nj & (1<<20)-1);
			if (!$j) {
				$direction = 3;
				$n5 += $nj5;
				$n2 += $nj2;
			} else {
				if ($njp5 <= $nj5) {
					$n5 += $njp5;
				} else {
					$n5 += $nj5;
					$direction = 1;
				}

				if ($njp2 <= $nj2) {
					$n2 += $njp2;
				} else {
					$n2 += $nj2;
					$direction += 2;
				}

			}
		}
		else {
			if ($j) {
				$n5 += $njp5;
				$n2 += $njp2;
			} else {
				$numbersRow[$j] = 0;
			}
		}
		$numbersRow[$j] = ($n5<<20) + $n2;
		$directionsArray[$i][$j] = chr($direction);
	}
}

$time2 = microtime(true);
//echo "first part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

$min2 = ($numbersRow[$n-1] & (1<<20)-1);
$min5 = ($numbersRow[$n-1]>>20);

function findMinPath(&$a, $i, $j, $bit) {
	if ($i==0 && $j==0) {
		return '';
	} elseif ($i==0) {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	} elseif ($j==0) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} elseif (ord($a[$i][$j]) & $bit) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} else {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	}
}

$min = min($min2, $min5);
$path = '';
if ($min == $min2) {
	$path = findMinPath($directionsArray, $n-1, $n-1, 2);
} else {
	$path = findMinPath($directionsArray, $n-1, $n-1, 1);
}

$time2 = microtime(true);
//echo "second part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

echo $min . PHP_EOL . $path;

<?php

/**
 * http://codeforces.com/problemset/problem/2/B
 *
 * Задана квадратная матрица n × n, состоящая из неотрицательных целых чисел.
 * Вам надо найти такой путь на ней, который
 * начинается в левой верхней ячейке матрицы;
 * каждой следующей ячейкой имеет правую или нижнюю от текущей;
 * заканчивается в правой нижней клетке.
 *
 * Кроме того, если перемножить все числа вдоль пути и посмотреть на
 * получившиеся произведение, то это число должно быть как можно менее «круглым».
 * Иными словами оно должно заканчиваться на наименьшее возможное количество нулей.
 */

define('DEBUG', 0);

function doLog($log) {
	if (DEBUG) {
		echo "[" . microtime(true) ."] " . $log . "\n";
	}
}

function dumpArray($a, $n) {
	if (DEBUG) {
		for ($i = 0; $i<$n; $i++) {
			for ($j = 0; $j<$n; $j++) {
				echo "\t{$a[$i][$j]}";
			}
			echo "\n";
		}
		echo "\n";
	}
}

$numbersRow2 = [];
$numbersRow5 = [];
$directionsArray = [];

$n = trim(fgets(STDIN));

$time = microtime(true);

//$numString = explode(' ' , trim(fgets(STDIN)));
//$format = str_repeat('%d', $n);
$wasZero = [];
for ($i = 0; $i<$n; $i++) {
	$directionsArray[$i] = str_repeat(' ', $n);
	$numString = explode(' ' , trim(fgets(STDIN)));
	//$numString = sscanf(trim(fgets(STDIN)), $format);
	for ($j = 0; $j<$n; $j++) {
		$num = $numString[$j];
		$n2 = $n5 = 0;

		if ($num==0) {
			$n2 = $n5 = 0;
			$wasZero = [$i, $j];
		} else {
			while ($num && (($num & 1) == 0)) {
				$n2++;
				$num>>=1;
			}

			while ($num && ($num%5 == 0)) {
				$n5++;
				$num /= 5;
			}
		}

		if ($j>0) {
			//$njp = $numbersRow[$j-1];
			$njp5 = $numbersRow5[$j-1];
			$njp2 = $numbersRow2[$j-1];
		}
		$direction = 0;

		if ($i) {
			//$nj = $numbersRow[$j];
			$nj5 = $numbersRow5[$j];
			$nj2 = $numbersRow2[$j];
			if (!$j) {
				$direction = 3;
				$n5 += $nj5;
				$n2 += $nj2;
			} else {
				if ($njp5 <= $nj5) {
					$n5 += $njp5;
				} else {
					$n5 += $nj5;
					$direction = 1;
				}

				if ($njp2 <= $nj2) {
					$n2 += $njp2;
				} else {
					$n2 += $nj2;
					$direction += 2;
				}

			}
		}
		else {
			if ($j) {
				$n5 += $njp5;
				$n2 += $njp2;
			} else {
				$numbersRow2[$j] = 0;
				$numbersRow5[$j] = 0;
			}
		}
		$numbersRow2[$j] = $n2;
		$numbersRow5[$j] = $n5;
		$directionsArray[$i][$j] = chr($direction);
	}
}

$time2 = microtime(true);
//echo "first part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

$min2 = $numbersRow2[$n-1];
$min5 = $numbersRow5[$n-1];

function findMinPath(&$a, $i, $j, $bit) {
	if ($i==0 && $j==0) {
		return '';
	} elseif ($i==0) {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	} elseif ($j==0) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} elseif (ord($a[$i][$j]) & $bit) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} else {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	}
}

$min = min($min2, $min5);

// учесть вариант когда в таблице есть нуль (т.е. произведение по этому пути будет 0),
// но существует путь совсем без нулей
if ($min>1 && $wasZero) {
	$min = 1;
	$path = str_repeat('R', $wasZero[1]) . str_repeat('D', $n) . str_repeat('R', $n - $wasZero[1]);
} else {
	$path = '';
	if ($min == $min2) {
		$path = findMinPath($directionsArray, $n-1, $n-1, 2);
	} else {
		$path = findMinPath($directionsArray, $n-1, $n-1, 1);
	}
}

$time2 = microtime(true);
//echo "second part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

echo $min . PHP_EOL . $path;

<?php

/**
 * http://codeforces.com/problemset/problem/2/B
 *
 * Задана квадратная матрица n × n, состоящая из неотрицательных целых чисел.
 * Вам надо найти такой путь на ней, который
 * начинается в левой верхней ячейке матрицы;
 * каждой следующей ячейкой имеет правую или нижнюю от текущей;
 * заканчивается в правой нижней клетке.
 *
 * Кроме того, если перемножить все числа вдоль пути и посмотреть на
 * получившиеся произведение, то это число должно быть как можно менее «круглым».
 * Иными словами оно должно заканчиваться на наименьшее возможное количество нулей.
 */

define('DEBUG', 0);

function doLog($log) {
	if (DEBUG) {
		echo "[" . microtime(true) ."] " . $log . "\n";
	}
}

function dumpArray($a, $n) {
	if (DEBUG) {
		for ($i = 0; $i<$n; $i++) {
			for ($j = 0; $j<$n; $j++) {
				echo "\t{$a[$i][$j]}";
			}
			echo "\n";
		}
		echo "\n";
	}
}

$numbersRow = [];
$directionsArray = [];

$n = trim(fgets(STDIN));

$time = microtime(true);

//$numString = explode(' ' , trim(fgets(STDIN)));
//$format = str_repeat('%d', $n);
for ($i = 0; $i<$n; $i++) {
	$directionsArray[$i] = str_repeat(' ', $n);
	$numString = explode(' ' , trim(fgets(STDIN)));
	//$numString = sscanf(trim(fgets(STDIN)), $format);
	for ($j = 0; $j<$n; $j++) {
		$num = $numString[$j];
		$n2 = $n5 = 0;

		while (($num & 1) == 0) {
			$n2++;
			$num>>=1;
		}

		while ($num%5 == 0) {
			$n5++;
			$num /= 5;
		}

		if ($j>0) {
			$njp = $numbersRow[$j-1];
			$njp5 = ($njp >> 15);
			$njp2 = ($njp & (1<<15)-1);
		}
		$direction = 0;

		if ($i) {
			$nj = $numbersRow[$j];
			$nj5 = ($nj >> 15);
			$nj2 = ($nj & (1<<15)-1);
			if (!$j) {
				$direction = 3;
				$n5 += $nj5;
				$n2 += $nj2;
			} else {
				if ($njp5 <= $nj5) {
					$n5 += $njp5;
				} else {
					$n5 += $nj5;
					$direction = 1;
				}

				if ($njp2 <= $nj2) {
					$n2 += $njp2;
				} else {
					$n2 += $nj2;
					$direction += 2;
				}

			}
		}
		else {
			if ($j) {
				$n5 += $njp5;
				$n2 += $njp2;
			} else {
				$numbersRow[$j] = 0;
			}
		}
		$numbersRow[$j] = ($n5<<15) + $n2;
		$directionsArray[$i][$j] = chr($direction);
	}
}

$time2 = microtime(true);
echo "first part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

$min2 = ($numbersRow[$n-1] & (1<<15)-1);
$min5 = ($numbersRow[$n-1]>>15);

function findMinPath(&$a, $i, $j, $bit) {
	if ($i==0 && $j==0) {
		return '';
	} elseif ($i==0) {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	} elseif ($j==0) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} elseif (ord($a[$i][$j]) & $bit) {
		return findMinPath($a, $i-1, $j, $bit) . 'D';
	} else {
		return findMinPath($a, $i, $j-1, $bit) . 'R';
	}
}

$min = min($min2, $min5);
$path = '';
if ($min == $min2) {
	$path = findMinPath($directionsArray, $n-1, $n-1, 2);
} else {
	$path = findMinPath($directionsArray, $n-1, $n-1, 1);
}

$time2 = microtime(true);
echo "second part: " . ($time2-$time) . PHP_EOL;
$time = $time2;

//echo $min . PHP_EOL . $path;


There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights.    Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1] Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly k consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such k consecutive planks that the sum of their heights is minimal possible.Write the program that finds the indexes of k consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).

The first line of the input contains integers n and k (1 ≤ n ≤ 1.5·105, 1 ≤ k ≤ n) — the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers h1, h2, ..., hn (1 ≤ hi ≤ 100), where hi is the height of the i-th plank of the fence.

Print such integer j that the sum of the heights of planks j, j + 1, ..., j + k - 1 is the minimum possible. If there are multiple such j's, print any of them.

NoteIn the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8.


Artem is building a new robot. He has a matrix $$$a$$$ consisting of $$$n$$$ rows and $$$m$$$ columns. The cell located on the $$$i$$$-th row from the top and the $$$j$$$-th column from the left has a value $$$a_{i,j}$$$ written in it. If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells contain the same value, where two cells are called adjacent if they share a side. Artem wants to increment the values in some cells by one to make $$$a$$$ good.More formally, find a good matrix $$$b$$$ that satisfies the following condition —   For all valid ($$$i,j$$$), either $$$b_{i,j} = a_{i,j}$$$ or $$$b_{i,j} = a_{i,j}+1$$$. For the constraints of this problem, it can be shown that such a matrix $$$b$$$ always exists. If there are several such tables, you can output any of them. Please note that you do not have to minimize the number of increments.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n, m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$)  — the number of rows and columns, respectively. The following $$$n$$$ lines each contain $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$a_{i,j}$$$ ($$$1 \leq a_{i,j} \leq 10^9$$$).

For each case, output $$$n$$$ lines each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$b_{i,j}$$$.

NoteIn all the cases, you can verify that no two adjacent cells have the same value and that $$$b$$$ is the same as $$$a$$$ with some values incremented by one.


Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s.

The first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only.

If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s. The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages.

<?php
$a = trim(fgets(STDIN));
$b = trim(fgets(STDIN));
$d = array();
for($x = 1; $x <= $b; $x++)
{
    $c = trim(fgets(STDIN));
    array_push($d, $c);
}
sort($d);
$e = strlen($a);
$f = 0;
for($x = 0; $x < $b; $x++)
{
    $f = substr($d[$x], 0, $e);
    if($f == $a)
    {
        $f = 1;
        break;
    }

}
if($f == 0)
{
    print $a;
}
else
{
    print $d[$x];
}
?>

<?php

while($s = fgets(STDIN)){
    $input .= $s;
}

$input = explode("\r\n", $input);
$s = $input[0];
unset($input[1]);
unset($input[0]);
$input = array_values($input);
$ss = implode("\r\n", $input);
/*/
$s = 'next';
$ss = "nextpermutation
nextelement";

//*/

$ss = explode("\r\n", $ss);
foreach($ss as $oneof) {
    if(substr($oneof, 0, strlen($s)) == $s)  $new[] = $oneof;
}

if(count($new) < 1) echo $s;

sort($new);
echo $new[0];

<?php

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

list($need) = fscanf($stdin, "%s");
list($count) = fscanf($stdin, "%d");

$regex = "/^$need/";

$ex = array();

for ($i=0; $i<$count; $i++) {
    list($str) = fscanf($stdin, "%s");
    if (preg_match($regex, $str)) {
        $ex[] = $str;
    }
}

$found = $need;
if ($ex) {
    sort($ex);
    $found = $ex[0];
}

echo "$found\n";

exit;

<?php
error_reporting("off");
//53A: Autocomplete
$s = trim(fgets(STDIN));
$n = trim(fgets(STDIN));
$lines = array();
$trimmed = array();
$matches = array();
for ($i = 0; $i < $n; $i++) {
    $lines[] = trim(fgets(STDIN));
}
$len = strlen($s);
foreach ($lines as $value) {
    if(substr($value, 0, $len) == $s) {
        $matches[] = $value;
        $trimmed[] = substr($value, $len);
    }
}

if (empty($trimmed)) {
    echo $s;
} else {
    asort($trimmed);
    $first = key($trimmed);
    echo $matches[$first];
}
?>

<?php
error_reporting("off");
//53A: Autocomplete
$s = trim(fgets(STDIN));
$n = trim(fgets(STDIN));
$lines = array();
$trimmed = array();
for ($i = 0; $i < $n; $i++) {
    $lines[] = trim(fgets(STDIN));
}
$len = strlen($s);
foreach ($lines as $value) {
    if(substr($value, 0, $len) == $s) {
        $trimmed[] = substr($value, $len);
    }
}

if (empty($trimmed)) {
    echo $s;
} else {
    asort($trimmed);
    $first = key($trimmed);
    echo $lines[$first];
}
?>


Given an array a1, a2, ..., an of n integers, find the largest number in the array that is not a perfect square.A number x is said to be a perfect square if there exists an integer y such that x = y2.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second line contains n integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — the elements of the array. It is guaranteed that at least one element of the array is not a perfect square.

Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.

NoteIn the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
rsort($b);
for($x = 0; $x < $a; $x++)
{
     $c = sqrt($b[$x]);
     $d = floor($c);
     if($c != $d)
     {
          print $b[$x];
          break;
     }
}
?>


In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction).Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.

The first line of the input contains n (2 ≤ n ≤ 1000) — number of bidders. The second line contains n distinct integer numbers p1, p2, ... pn, separated by single spaces (1 ≤ pi ≤ 10000), where pi stands for the price offered by the i-th bidder.

The single output line should contain two integers: index of the winner and the price he will pay. Indices are 1-based.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
arsort($b);
$c = array_keys($b);
rsort($b);
print $c[0] + 1 . " " . $b[1];
?>

<?php

$filename = 'php://stdin';

$f = fopen($filename, 'r');
$n = (int)fgets($f);

$last = false;
$pred = $max = false;

for ($i = 0; $i < $n; $i++) {
    $c = $s = '';
    while (!feof($f) && $c != ' ') {
        $s .= ($c = fgetc($f));
    }
    $s = (int) $s;
    if ($max === false) {
        $max = $s;
        $last = $i;
    }
    elseif ($max < $s) {
        $pred = $max;
        $max = $s;
        $last = $i;
    }
    elseif ($pred === false) {
        $pred = $s;
    }
    elseif ($pred < $s) {
        $pred = $s;
    }
}

echo ++$last . ' ' . $pred;


Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol.

The first line contains two integers n and m (1 ≤ n ≤ m ≤ 1000) — the length of the string s and the length of the string t correspondingly. The second line contains n lowercase English letters — string s. The third line contains m lowercase English letters — string t.

In the first line print single integer k — the minimal number of symbols that need to be replaced. In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.

<?php
$a=explode(' ',trim(fgets(STDIN)));
function num($a,$b){
    $n=0;
    $loop=strlen($a);
    for ($i=0;$i<$loop;$i++){
        if ($a[$i]!=$b[$i]){
            $n++;
        }
    }
    return $n;
}
$loop=$a[1]-$a[0];
$b=trim(fgets(STDIN));
$c=trim(fgets(STDIN));
$arr=array();
for ($i=0;$i<=$loop;$i++){
    $arr[$i]=num($b,substr($c,$i));
}
echo min($arr),"\n";
$loc=array_search(min($arr),$arr);
$n=0;
for ($i=0;$i<strlen($b);$i++){
    if ($b[$i]!=$c[$i+$loc]){
        echo $i+1;
        $n++;
        if ($n!=min($arr)){
            echo ' ';
        }
        else{
            break;
        }
    }
}
?>

<?php
$a=explode(' ',trim(fgets(STDIN)));
function num($a,$b){
    $n=0;
    $loop=strlen($a);
    for ($i=0;$i<$loop;$i++){
        if ($a[$i]!=$b[$i]){
            $n++;
        }
    }
    return $n;
}
$loop=$a[1]-$a[0];
$b=trim(fgets(STDIN));
$c=trim(fgets(STDIN));
$arr=array();
for ($i=0;$i<=$loop;$i++){
    $arr[$i]=num($b,substr($c,$i));
}
echo min($arr),"\n";
$loc=array_search(min($arr),$arr);
$n=0;
for ($i=0;$i<strlen($b);$i++){
    if ($b[$i]!=$c[$i+$loc]){
        echo $i+$loc;
        $n++;
        if ($n!=min($arr)){
            echo ' ';
        }
        else{
            break;
        }
    }
}
?>


Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai.Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.

The first line contains a single positive integer n (1 ≤ n ≤ 5000) — the number of exams Valera will take. Each of the next n lines contains two positive space-separated integers ai and bi (1 ≤ bi < ai ≤ 109) — the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly.

Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.

NoteIn the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject.

<?php
$exams_count = trim(fgets(STDIN));
$days = array();
for ($i=0; $i<$exams_count; $i++) {
    $days[] = explode(" ", trim(fgets(STDIN)));
}

$c = array();
for ($i=0; $i<2; $i++) {
    for ($j=0; $j<$exams_count; $j++) {
        $c[$i][$j] = $days[$j][$i];
    }
}
array_multisort($c[0], SORT_ASC, $c[1]); //Сортируем по дате фактической сдачи
//print_r($c);

$best = -1;
for ($i = 0; $i < $exams_count; $i++) {
    if ($best <= $c[1][$i]) {
        $best = $c[1][$i];
    } else {
        $best = $c[0][$i];
    }
}

echo $best;
?>

<?php

$n = fgets(STDIN);
$ab = array();
for ($i = 0; $i < $n; $i++) {
	$row = explode(" ", fgets(STDIN));
	$row[0] += 0;
	$row[1] += 0;
	$ab[] = $row;
}
$a = array();
$b = array();
foreach ($ab as $key => $row) {
    $a[$key]  = $row[0];
    $b[$key] = $row[1];
}
array_multisort($a, SORT_ASC, $b, SORT_ASC, $ab);
unset($a);
unset($b);
$prevDate = -1;
for($i = 0; $i < $n; $i++) {
	if($ab[$i][1] <= $ab[$i][0] && $ab[$i][1] >= $prevDate) {
		$prevDate = $ab[$i][1];
	} else  {
		$prevDate = $ab[$i][0];
	}
}
echo $prevDate;

?>

<?php

$n = fgets(STDIN);
$ab = array();
for ($i = 0; $i < $n; $i++) {
	$row = explode(" ", fgets(STDIN));
	$row[0] += 0;
	$row[1] += 0;
	$ab[] = $row;
}
$a = array();
$b = array();
foreach ($ab as $key => $row) {
    $a[$key]  = $row[0];
    $b[$key] = $row[1];
}
array_multisort($a, SORT_ASC, $b, SORT_ASC, $ab);
$prevDate = -1;
foreach ($ab as $elem) {
	$a = $elem[0];
	$b = $elem[1];
	if($b <= $a && $b >= $prevDate) {
		$prevDate = $b;
	} else  {
		$prevDate = $a;
	}
}
echo $prevDate;
?>

<?php
$exams_count = trim(fgets(STDIN));
$days = array();
for ($i=0; $i<$exams_count; $i++) {
	$days[] = explode(" ", trim(fgets(STDIN)));
}
/*$exams_count = 3;
$test = array("6 1", "5 2", "4 3");
$days = array();
for ($i=0; $i<$exams_count; $i++) {
	$days[] = explode(" ", $test[$i]);
}*/
//print_r($days);
//echo "

";
$c = array();
for ($i=0; $i<2; $i++) {
	for ($j=0; $j<$exams_count; $j++) {
		$c[$i][$j] = $days[$j][$i];
	}
}
//print_r($c);
array_multisort($c[0], SORT_ASC, $c[1]);
//echo "

";
//print_r($c);
$flag = false;
for ($i = 0; $i < $exams_count-1; $i++) {
    if ($c[1][$i] > $c[1][$i + 1]) {
        $flag = true;
        break;
    }
}
if ($flag) {
	echo $c[0][$exams_count-1];
} else {
	echo $c[1][$exams_count-1];
}
?>

<?php

$n = fgets(STDIN);
$a2b = array();
for ($i = 0; $i < $n; $i++) {
	list($a, $b) = explode(" ", fgets(STDIN));
	$a2b[$a] = $b;
}
ksort($a2b);
$prevDate = -1;
foreach ($a2b as $a => $b) {
	if($b <= $a && $b >= $prevDate) {
		$prevDate = $b;
	} else  {
		$prevDate = $a;
	}
}
echo $prevDate;
?>

<?php

$n = fgets(STDIN);
$ab = array();
for ($i = 0; $i < $n; $i++) {
	$row = explode(" ", fgets(STDIN));
	$row[0] += 0;
	$row[1] += 0;
	$ab[] = $row;
}
$a = array();
$b = array();
foreach ($ab as $key => $row) {
    $a[$key]  = $row[0];
    $b[$key] = $row[1];
}
array_multisort($a, SORT_ASC, $b, SORT_ASC, $ab);
unset($a);
unset($b);
$prevDate = -1;
for($i = 0; $i < $n; $i++) {
	if($ab[$i][1] <= $ab[$i][0] && $ab[$i][1] >= $prevDate) {
		$prevDate = $ab[$i][1];
	} else  {
		$prevDate = $ab[$i][0];
	}
}
echo $prevDate." ".  (memory_get_peak_usage()/1024)."\n";

?>


You are given a multiset $$$S$$$ initially consisting of $$$n$$$ distinct non-negative integers. A multiset is a set, that can contain some elements multiple times.You will perform the following operation $$$k$$$ times:   Add the element $$$\lceil\frac{a+b}{2}\rceil$$$ (rounded up) into $$$S$$$, where $$$a = \operatorname{mex}(S)$$$ and $$$b = \max(S)$$$. If this number is already in the set, it is added again. Here $$$\operatorname{max}$$$ of a multiset denotes the maximum integer in the multiset, and $$$\operatorname{mex}$$$ of a multiset denotes the smallest non-negative integer that is not present in the multiset. For example:    $$$\operatorname{mex}(\{1,4,0,2\})=3$$$;   $$$\operatorname{mex}(\{2,5,1\})=0$$$. Your task is to calculate the number of distinct elements in $$$S$$$ after $$$k$$$ operations will be done.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1\le n\le 10^5$$$, $$$0\le k\le 10^9$$$) — the initial size of the multiset $$$S$$$ and how many operations you need to perform. The second line of each test case contains $$$n$$$ distinct integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_i\le 10^9$$$) — the numbers in the initial multiset. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the number of distinct elements in $$$S$$$ after $$$k$$$ operations will be done.

<?php

$times = (int) trim(fgets(STDIN));
for ($idx = 0; $idx < $times; ++$idx) {
    list($ni[], $ki[]) = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $ai[] = array_map('intval', explode(' ', trim(fgets(STDIN))));
}
for ($idx = 0; $idx < $times; ++$idx) {
    $n = &$ni[$idx];
    $k = &$ki[$idx];
    $a = &$ai[$idx];
    $m = max($a);
    $mex = $m + 1;
    $b = array_flip($a);
    for ($i = 0; $i < $m; ++$i) {
        if (!isset($b[$i])) {
            $mex = $i;
            break;
        }
    }
    if ($mex == $m + 1) {
        echo $m + $k + 1 .PHP_EOL;
    } else {
        $k > 0 && $a[] = ceil(($mex + $m) / 2);
        echo count(array_unique($a)).PHP_EOL;
    }
}

<?php
$fileName = 'php://stdin';
$file = fopen($fileName, "r");

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

for ($i = 0; $i < $t; $i++) {
  list($n, $k) = explode(" ", trim(fgets($file)));
  $s = explode(" ", trim(fgets($file)));
  sort($s);
  $p = 0; $m = 0; $r = 0; $mex = 0;

  if ($k == 0) {
    $r = array_unique($s);
    echo count($r).PHP_EOL;
  } else {

    if ($s[0] != 0) {
      $m = ceil($s[count($s) - 1] / 2);
      array_push($s, $m);
      $r = array_unique($s);
      echo count($r).PHP_EOL;

    } else {
    foreach($s as $key => $val) {
      if ($key != $val) { $p = 1; $mex = $key; break; }
    }

    if ($p == 1) {
      $m = ceil(($mex + $s[count($s) - 1]) / 2);
      array_push($s, $m);
      $r = array_unique($s);
      echo count($r).PHP_EOL;
    } else {
      $r = array_unique($s);
      echo count($r) + $k.PHP_EOL;
    }
    }
  }
}
?>

<?php
$fileName = 'php://stdin';
$file = fopen($fileName, "r");

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

for ($i = 0; $i < $t; $i++) {
  list($n, $k) = explode(" ", trim(fgets($file)));
  $s = explode(" ", trim(fgets($file)));
  sort($s);
  $p = 0; $m = 0; $r = 0; $mex = 0;

  if ($s[0] != 0 || $k == 0) {
    $r = array_unique($s);
    echo count($r).PHP_EOL;
  } else {

    foreach($s as $key => $val) {
      if ($key != $val) { $p = 1; $mex = $key; break; }
    }

    if ($p == 1) {
      $m = ceil(($mex + $s[count($s) - 1]) / 2);
      array_push($s, $m);
      $r = array_unique($s);
      echo count($r).PHP_EOL;
    } else {
      $r = array_unique($s);
      echo count($r) + $k.PHP_EOL;
    }
  }
}
?>


Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland.Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of m pieces of paper in the garland. Calculate what the maximum total area of the pieces of paper in the garland Vasya can get.

The first line contains a non-empty sequence of n (1 ≤ n ≤ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≤ m ≤ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make.

Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer.

NoteIn the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6.In the second test sample Vasya cannot make a garland at all — he doesn't have a sheet of color z.

<?php
define('LOCAL_ENV', false);
if (LOCAL_ENV) {
    error_reporting(E_ALL & !E_NOTICE);
//    $test = <<<INPUT
//4.147 2.8819
//6
//INPUT;
    $test = <<<INPUT
aaabbacaa
aabbccac
INPUT;
    $stdin = fopen('php://temp/in', 'rw');
    fwrite($stdin, $test);
    rewind($stdin);
} else {
    error_reporting(0);
    $stdin = STDIN;
}
define('MY_STDIN', $stdin);

$a = trim(fgets(MY_STDIN));
$b = trim(fgets(MY_STDIN));
$la = strlen($a); $lb = strlen($b);
$ca = $cb = array();
for ($i = 0; $i < $la; $i++) {$ca[$a{$i}]++; };
for ($i = 0; $i < $lb; $i++) {$cb[$b{$i}]++; };
$ans = 0;

foreach ($cb as $c => $val) {
    if (!isset($ca[$c])) {
        echo "-1";
        exit();
    }
    if ($val < $ca[$c]) {
        $ans += $val; //$ca[$c] - ($ca[$c] % $val);
    } else if ($val == $ca[$c]) {
        $ans += $val;
    } else {
        $ans += $ca[$c];
    }
}
echo $ans;

<?php

$p = str_split(trim(fgets(STDIN)));
$d = str_split(trim(fgets(STDIN)));

$np = array_count_values($p);

$a = 0;
foreach($d as $dd)
{
	if(! @isset($np[$dd]))
	{
		$a = 0;
		break;
	}

	$a += ($np[$dd] > 0);
	$np[$dd] = max(0, --$np[$dd]);
}

echo ($a == 0) ? "-1" : $a;
echo PHP_EOL;

<?php

$p = str_split(trim(fgets(STDIN)));
$d = str_split(trim(fgets(STDIN)));

$np = array_count_values($p);
$nd = array_count_values($d);
$ni = array_keys(array_intersect_key($np, $nd));

$a = 0;
foreach($ni as $ii)
{
	$a += min($np[$ii], $nd[$ii]);
}

echo ($a == 0) ? "-1" : $a;
echo PHP_EOL;

<?php

$p = str_split(trim(fgets(STDIN)));
$d = str_split(trim(fgets(STDIN)));

$np = array_count_values($p);
$nd = array_count_values($d);
$ni = array_keys(array_intersect_key($np, $nd));

$a = 0;
foreach($ni as $ii)
{
	$a += min($np[$ii], $nd[$ii]);
}

echo $a . PHP_EOL;


You are given an array $$$a_1, a_2, \dots, a_n$$$, which is sorted in non-descending order. You decided to perform the following steps to create array $$$b_1, b_2, \dots, b_n$$$:   Create an array $$$d$$$ consisting of $$$n$$$ arbitrary non-negative integers.  Set $$$b_i = a_i + d_i$$$ for each $$$b_i$$$.  Sort the array $$$b$$$ in non-descending order. You are given the resulting array $$$b$$$. For each index $$$i$$$, calculate what is the minimum and maximum possible value of $$$d_i$$$ you can choose in order to get the given array $$$b$$$.Note that the minimum (maximum) $$$d_i$$$-s are independent of each other, i. e. they can be obtained from different possible arrays $$$d$$$.

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of arrays $$$a$$$, $$$b$$$ and $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$; $$$a_i \le a_{i+1}$$$) — the array $$$a$$$ in non-descending order. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$; $$$b_i \le b_{i+1}$$$) — the array $$$b$$$ in non-descending order. Additional constraints on the input:    there is at least one way to obtain the array $$$b$$$ from the $$$a$$$ by choosing an array $$$d$$$ consisting of non-negative integers;  the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print two lines. In the first line, print $$$n$$$ integers $$$d_1^{min}, d_2^{min}, \dots, d_n^{min}$$$, where $$$d_i^{min}$$$ is the minimum possible value you can add to $$$a_i$$$. Secondly, print $$$n$$$ integers $$$d_1^{max}, d_2^{max}, \dots, d_n^{max}$$$, where $$$d_i^{max}$$$ is the maximum possible value you can add to $$$a_i$$$. All $$$d_i^{min}$$$ and $$$d_i^{max}$$$ values are independent of each other. In other words, for each $$$i$$$, $$$d_i^{min}$$$ is just the minimum value among all possible values of $$$d_i$$$.


The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out — one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100, 2 ≤  n · m) — the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).

On the first line output integer k — the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m) — the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2). Then print nm + 1 lines containing 2 numbers each — the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.


One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.

The first line of the input contains integer n (1 ≤ n ≤ 200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive. We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.

Print a single integer — the maximum length of a repost chain.

5
tourist reposted Polycarp
Petr reposted Tourist
WJMZBMR reposted Petr
sdya reposted wjmzbmr
vepifanov reposted sdya

6
Mike reposted Polycarp
Max reposted Polycarp
EveryOne reposted Polycarp
111 reposted Polycarp
VkCup reposted Polycarp
Codeforces reposted Polycarp

<?php
function getLevel($reposts, $name){
    foreach($reposts as $repost){
        if(preg_match('|'.$repost['name'].'|i', $name) && strlen($name) == strlen($repost['name'])){
            return $repost['level'];
        }
    }
}
$n = fgets(STDIN);
if($n == 0){
    $maxLevel = 1;
}
for($i = 0; $i < $n; ++$i){
    $t = explode(' reposted ', fgets(STDIN));
    $t[1] = str_replace(array("\r", "\n"), '', $t[1]);
    if($i == 0){
        $reposts[] = array(
            'name' => $t[1],
            'level' => 1
        );
        $maxLevel = 1;
    }
    $level = getLevel($reposts, $t[1])+1;
    if($level > $maxLevel){
        $maxLevel = $level;
    }
    $reposts[] = array(
        'name' => $t[0],
        'level' => $level
    );
}
echo $maxLevel;
?>

<?PHP

// $fileIN = fopen("in.txt", "r");
// $fileOUT = fopen("out.txt", "w");
$fileIN = fopen("php://stdin", "r");
$fileOUT = fopen("php://stdout", "w");

$N = trim(fgets($fileIN));

$mapa = array();

$mapa[strtoupper("Polycarp")] = 1;

$rs = 0;

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

    $s = trim(fgets($fileIN));
    $data = explode(" ", $s);

    if (!isset($mapa[strtoupper($data[0])])) {
        $mapa[strtoupper($data[0])] = 0;
    }
    if (!isset($mapa[strtoupper($data[2])])) {
        $mapa[strtoupper($data[2])] = 0;
    }

    $mapa[strtoupper($data[0])] = $mapa[strtoupper($data[2])] + 1;

    if ($mapa[strtoupper($data[0])] > $rs) {
        $rs = $mapa[strtoupper($data[0])];
    }

}

fprintf($fileOUT, $rs . "\n");

fclose($fileIN);
fclose($fileOUT);

?>

<?php
$chain = array(
    'polycarp' => 1
);
$max = 1;
$count = (int) fgets(STDIN);
for ($i = 0; $i < $count; $i++) {
    list($name1, $name2) = explode("reposted", fgets(STDIN));
    $name2 = strtolower(trim($name2));
    if (! isset($chain[$name2])) continue;
    $name1 = strtolower(trim($name1));
    $chain[$name1] = $chain[$name2] + 1;
    if ($chain[$name1] > $max) $max = $chain[$name1];
}
echo $max;
?>

<?php
$rCount=fgets(STDIN);
$Reposts=array("polycarp"=>1);
$max=1;
for($i=0;$i<$rCount;$i++)
{
    list($to,$from)=explode(" reposted ",strtolower(fgets(STDIN)));
    $from=trim($from);
        $to=trim($to);
    $Reposts[$to]=$Reposts[$from]+1;
    if($Reposts[$to]>$max)
    {
    $max=$Reposts[$to];
    }
}
echo $max;
?>

<?php
$fd = fopen("php://stdin", 'r');
$repostsCount = trim(fgets($fd));

$reposts = [];
while (!feof($fd)) {
    list($to,, $from) = explode(" ", strtolower(trim(fgets($fd))));
    if (!isset($reposts[$from])) {
        $reposts[$from] = [];
    }
    $reposts[$from][] = $to;
}

function countRepostsDepth($name, $reposts) {
    if (empty($reposts[$name])) {
        return 1;
    }
    $max = 1;
    foreach ($reposts[$name] as $user) {
        $child = 1 + countRepostsDepth($user, $reposts);
        if ($child > $max) {
            $max = $child;
        }
    }
    return $max;
}
echo countRepostsDepth("polycarp", $reposts);

<?
$line=array();
$max=0;

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

for($i=1;$i<=$maximum;$i++) {
$line=strtolower(rtrim(fgets($handle)));
$rep[$i]=explode(" ",$line);

$num[0][$i]=1;
}

for($i = 1; $i <= $maximum; $i++)
{
$num[1][$i] = $num[0][$i] + 1;

  for ($j = ($i + 1); $j <= $maximum; $j++)
   if ($rep[$j][2] == $rep[$i][0])
    $num[0][$j] = $num[1][$i];

}

 for ($i = 1; $i <= $maximum; $i++)
  if ($num[1][$i] > $max)
   $max = $num[1][$i];
$stdout=fopen("php://stdout",'w');
echo $max;
?>

<?php
$n = trim(fgets(STDIN));
$regExp = "/(\S+) reposted (\S+)/";
$arr = array();
for ($i = 0; $i<$n; $i++) {
    $line = strtolower(trim(fgets(STDIN)));
    preg_match($regExp,$line, $matches);
    $arr []= array($matches[2],$matches[1]);
}
$root = array("polycarp");

$temp = array();
$counter=1;
for ($i = 0; $i<$n; $i++) {
    if (in_array($arr[$i][0], $root)){
        $temp []= $arr[$i][1];
        $arr[$i][0] = null;
    }
    if($i == $n-1 && count($temp)>0){
        $root = $temp;
        $temp = array();
        $i=0;
        $counter++;
    }
}

printf("%d",$counter);
?>

<?php

        $n = (int)fgets(STDIN);
        $a = array('polycarp' => 1 );
        $max = 1;
        for( $i = 0; $i < $n; $i++ ){
                list($who, $from) = explode(' reposted ', strtolower (trim( fgets(STDIN) ) ) );
                $a[$who] = $a[$from]+1;
                if( $max < $a[$who] ){
                        $max = $a[$who];
                }
        }

        print $max;

?>

<?php

$n = (int)trim(fgets(STDIN));
$arr = array('polycarp' => 1);
$max = 1;

for ( $i = 0; $i < $n; ++$i ) {
	$repost = trim(fgets(STDIN));
	$name = explode(' reposted ', $repost);
	$fName = trim(strtolower( $name[0] ) );
	$sName = trim( strtolower( $name[1] ) );

	$arr[$fName] = $arr[$sName] + 1;
}

echo max($arr);

<?php
$n = (int) rtrim(fgets(STDIN));
$a['polycarp'] = 1;
for ($i = 0; $i < $n; $i++) {
	$d = explode(' reposted ', strtolower(rtrim(fgets(STDIN))));
	$a[$d[0]] = $a[$d[1]] + 1;
}
echo @max($a);
?>

<?php
$n = (int) rtrim(fgets(STDIN));
$a['polycarp'] = 1;
for ($i = 0; $i < $n; $i++) {
	$u = explode(' reposted ', strtolower(rtrim(fgets(STDIN))));
	$a[$u[0]] = $a[$u[1]] + 1;
}
echo max($a);
?>

<?php
for ($i = 0, $n = (int) rtrim(fgets(STDIN)), $a['polycarp'] = 1; $i < $n; $i++, $m = explode(' reposted ', strtolower(rtrim(fgets(STDIN)))), $a[$m[0]] = $a[$m[1]] + 1);
echo max($a);
?>

<?php
$n = (int) fgets(STDIN);
$r['polycarp'] = 1;
for ($i = 0; $i < $n; $i++) {
	$u = explode(' reposted ', strtolower(rtrim(fgets(STDIN))));
	$r[$u[0]] = $r[$u[1]] + 1;
	if ($m < $r[$u[0]]) $m = $r[$u[0]];
}
echo $m;
?>

<?php

$n = trim(fgets(STDIN));

$list = array(
    'polycarp' => 1
);
$max = 1;
for($i = 0; $i < $n; $i++){
    $line = trim(fgets(STDIN));
    $exp = explode(' reposted ', $line);
    $cur = $list[strtolower($exp[1])]+1;
    $list[strtolower($exp[0])] = $cur;
    if($cur > $max) $max = $cur;
}
echo $max;

<?php
    //
                $dir = fopen("php://stdin", 'r');
                $input = stream_get_contents($dir);

//    $input = '5
//tourist reposted Polycarp
//Petr reposted Tourist
//WJMZBMR reposted Petr
//sdya reposted wjmzbmr
//vepifanov reposted sdya';

    //    $nr = 0;
    //    preg_match('/^[0-9]+/', $input, $nr);
    //    $nr = (int)$nr[0];

    $arr = explode(PHP_EOL, $input);
    $nr = (int)$arr[0];

    unset($arr[0]);
//    print_r($arr);

    $root = array('polycarp' => 1);

    foreach ($arr as $line) {
//        var_dump($line);
        preg_match('/([a-zA-Z0-9]{2,24}) reposted ([a-zA-Z0-9]{2,24})$/', $line, $matches);

//        var_dump($matches);
        $first = strtolower($matches[1]);
        $second = strtolower($matches[2]);
        $root[$first] = $root[$second] + 1;
    }

//    var_dump($root);
    echo max(array_values($root));

<?php
$n = (int) trim(fgets(STDIN));
$q['polycarp'] = 1;
for($i = 0; $i<$n; $i++){
    $p = explode(' reposted ', strtolower(trim(fgets(STDIN))));
    $q[$p[0]] = $q[$p[1]]+1;
}
echo max($q);
?>

<?
$line=array();
$max=0;

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

for ($i = 1; $i <= $maximum; $i++) $num[0][$i] = 1;

for($i=1;$i<=$maximum;$i++) {
$line=fgets($handle);

$line=rtrim($line);

$rep[$i]=explode(" ",$line);
$rep[$i]=array_map('strtolower', $rep[$i]);
}

for($i = 1; $i <= $maximum; $i++)
{
$num[1][$i] = $num[0][$i] + 1;

  for ($j = ($i + 1); $j <= $maximum; $j++)
   if ($rep[$j][2] == $rep[$i][0])
    $num[0][$j] = $num[1][$i];

}

 for ($i = 1; $i <= $maximum; $i++)
  if ($num[1][$i] > $max)
   $max = $num[1][$i];

echo $max;
?>

<?php
	$r = array('polycarp' => 1);
	$n = (int)fgets(STDIN);
	$max = 1;
	for($i = 0; $i < $n; $i++) {
		$line = fgets(STDIN);
		$params = explode(' reposted ', $line);
		$name1 = strtolower(trim($params[0]));
		$name2 = strtolower(trim($params[1]));
		$r[$name1] = $r[$name2] + 1;
		if ($r[$name1] > $max) {
			$max = $r[$name1];
		}
	}
	echo $max;
?>

<?php
    $n = fgets(STDIN);
    $n = (int) $n;
    $arr['polycarp'] = 1;
    $max = 1;
    for($i = 0; $i < $n; $i++)
    {
        $read = explode(" ", fgets(STDIN));
        $str1 = rtrim(strtolower ($read[0]));
        $str2 = rtrim(strtolower ($read[2]));
        $arr [$str1] = $arr [$str2] + 1;
    }
    foreach ($arr as $index => $value)
    {
        if ($value > $max)
            $max = $value;
    }
    echo $max;
?>

<?php

$n = (int)trim(fgets(STDIN));
$counters = array();

for ($i = 0; $i < $n; $i++)
{
	$reposts[$i] = explode(' reposted ', strtolower(trim(fgets(STDIN))));
	$counters[$reposts[$i][0]] = 0;
	$counters[$reposts[$i][1]] = 0;
}

getAmount('polycarp', $reposts, $n, 1, $counters);

echo max($counters);

function getAmount($name, $reposts, $n, $amount, &$counters)
{
	for ($i = 0; $i < $n; $i++)
	{
		if ($reposts[$i][1] == $name)
		{
			$counters[$reposts[$i][0]] = $amount + 1;
			getAmount($reposts[$i][0], $reposts, $n, $counters[$reposts[$i][0]], $counters);
		}
	}
}

?>

<?php
function getLevel($reposts, $name){
    foreach($reposts as $repost){
        if(preg_match('|'.$repost['name'].'|i', $name)){
            return $repost['level'];
        }
    }
}
$n = fgets(STDIN);
if($n == 0){
    $maxLevel = 0;
}
for($i = 0; $i < $n; ++$i){
    $t = explode(' reposted ', fgets(STDIN));
    if($i == 0){
        $reposts[] = array(
            'name' => $t[1],
            'level' => 1
        );
        $maxLevel = 1;
    }
    $level = getLevel($reposts, $t[1])+1;
    if($level > $maxLevel){
        $maxLevel = $level;
    }
    $reposts[] = array(
        'name' => $t[0],
        'level' => $level
    );
}
echo $maxLevel;
?>

<?php
    //
                $dir = fopen("php://stdin", 'r');
                $input = stream_get_contents($dir);

//    $input = '13
//uuuu reposted polycarp
//uuuuuuuuuu reposted uuuu
//uuuuuuuuuuuuuuuuuuuuuuuu reposted uuuuuuuuuu
//vvv reposted uuuuuuuuuuuuuuuuuuuuuuuu
//yyyyyyyyyyyyyyy reposted uuuuuuuuuuuuuuuuuuuuuuuu
//vvvvvvvvvvvvvvvv reposted yyyyyyyyyyyyyyy
//xxxxxxxxxxxxxxxxxxxx reposted uuuuuuuuuu
//uuuuuuuuuuuuuu reposted xxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxx reposted uuuu
//uuuuuuuuuuu reposted vvv
//zzzzzzzzzzzzzzz reposted uuuuuuuuuuu
//wwwwwwww reposted uuuuuuuuuuuuuu
//yyyyyyyyyyyy reposted vvvvvvvvvvvvvvvv';

    //    $nr = 0;
    //    preg_match('/^[0-9]+/', $input, $nr);
    //    $nr = (int)$nr[0];

    $arr = explode(PHP_EOL, $input);
    $nr = (int)$arr[0];

    unset($arr[0]);
//    print_r($arr);

    $root = array('polycarp' => 1);

    foreach ($arr as $line) {
        preg_match('/^([a-z0-9]{2,24}) reposted ([a-z0-9]{2,24})$/', $line, $matches);
        $first = strtolower($matches[1]);
        $second = strtolower($matches[2]);
        $root[$first] = $root[$second] + 1;
    }

//    var_dump($root);
    echo max(array_values($root));

<?php

            $dir = fopen("php://stdin", 'r');
            $input = stream_get_contents($dir);

//    $input = '13
//uuuu reposted polycarp
//uuuuuuuuuu reposted uuuu
//uuuuuuuuuuuuuuuuuuuuuuuu reposted uuuuuuuuuu
//vvv reposted uuuuuuuuuuuuuuuuuuuuuuuu
//yyyyyyyyyyyyyyy reposted uuuuuuuuuuuuuuuuuuuuuuuu
//vvvvvvvvvvvvvvvv reposted yyyyyyyyyyyyyyy
//xxxxxxxxxxxxxxxxxxxx reposted uuuuuuuuuu
//uuuuuuuuuuuuuu reposted xxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxx reposted uuuu
//uuuuuuuuuuu reposted vvv
//zzzzzzzzzzzzzzz reposted uuuuuuuuuuu
//wwwwwwww reposted uuuuuuuuuuuuuu
//yyyyyyyyyyyy reposted vvvvvvvvvvvvvvvv';

    $nr = 0;
    preg_match('/^[0-9]+/', $input, $nr);
    $nr = (int)$nr[0];

    $root = array('polycarp' => 1);

    $max = 1;
    $maxOld = 0;
    while ($max != $maxOld) {
        $maxOld = $max;

        foreach ($root as $key => $value) {
            if ($value == $max) {

                $namesArray = null;
                preg_match_all("/([a-z0-9]*) .* $key/i", $input, $namesArray);

                foreach ($namesArray[1] as $item) {
                    $root[$item] = $root[$key] + 1;
                    $input = preg_replace("/$item reposted $key/", '', $input, 1);
                }

                foreach ($root as $n) {
                    if ($n > $max) {
                        $max = $n;
                    }
                }
            }
        }
    }

    echo $max;

<?php

    $dir = fopen("php://stdin", 'r');
    $input = file_get_contents($dir);
    $input = explode("\n", $input);

    $nr = $input[0];

    $root = 'polycarp';

    for ($i = 1; $i <= $nr; $i++) {
        $name = null;
        preg_match("/^([a-z0-9]{2,24}) .*$root/",strtolower($input[$i]), $name);

        echo $name;
    }

<?php

            $dir = fopen("php://stdin", 'r');
            $input = stream_get_contents($dir);

//    $input = '13
//uuuu reposted polycarp
//uuuuuuuuuu reposted uuuu
//uuuuuuuuuuuuuuuuuuuuuuuu reposted uuuuuuuuuu
//vvv reposted uuuuuuuuuuuuuuuuuuuuuuuu
//yyyyyyyyyyyyyyy reposted uuuuuuuuuuuuuuuuuuuuuuuu
//vvvvvvvvvvvvvvvv reposted yyyyyyyyyyyyyyy
//xxxxxxxxxxxxxxxxxxxx reposted uuuuuuuuuu
//uuuuuuuuuuuuuu reposted xxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxx reposted uuuu
//uuuuuuuuuuu reposted vvv
//zzzzzzzzzzzzzzz reposted uuuuuuuuuuu
//wwwwwwww reposted uuuuuuuuuuuuuu
//yyyyyyyyyyyy reposted vvvvvvvvvvvvvvvv';

    $nr = 0;
    preg_match('/^[0-9]+/', $input, $nr);
    $nr = (int)$nr[0];

    $root = array('polycarp' => 1);

    $max = 1;
    $maxOld = 0;
    while ($max != $maxOld) {
        $maxOld = $max;

        foreach ($root as $key => $value) {
            if ($value == $max) {

                $namesArray = null;
                preg_match_all("/([a-z0-9]*) reposted $key/i", $input, $namesArray);

                foreach ($namesArray[1] as $item) {
                    $root[$item] = $root[$key] + 1;
                    $input = preg_replace("/$item reposted $key/", '', $input, 1);
                }

                foreach ($root as $n) {
                    if ($n > $max) {
                        $max = $n;
                    }
                }
            }
        }
    }

    echo $max;

<?php

            $dir = fopen("php://stdin", 'r');
            $input = stream_get_contents($dir);

//    $input = '13
//uuuu reposted polycarp
//uuuuuuuuuu reposted uuuu
//uuuuuuuuuuuuuuuuuuuuuuuu reposted uuuuuuuuuu
//vvv reposted uuuuuuuuuuuuuuuuuuuuuuuu
//yyyyyyyyyyyyyyy reposted uuuuuuuuuuuuuuuuuuuuuuuu
//vvvvvvvvvvvvvvvv reposted yyyyyyyyyyyyyyy
//xxxxxxxxxxxxxxxxxxxx reposted uuuuuuuuuu
//uuuuuuuuuuuuuu reposted xxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxx reposted uuuu
//uuuuuuuuuuu reposted vvv
//zzzzzzzzzzzzzzz reposted uuuuuuuuuuu
//wwwwwwww reposted uuuuuuuuuuuuuu
//yyyyyyyyyyyy reposted vvvvvvvvvvvvvvvv';

    $nr = 0;
    preg_match('/^[0-9]+/', $input, $nr);
    $nr = (int)$nr[0];

    $root = array('polycarp' => 1);

    $max = 1;
    $maxOld = 0;
    while ($max != $maxOld) {
        $maxOld = $max;

        foreach ($root as $key => $value) {
            if ($value == $max) {

                $namesArray = null;
                preg_match_all("/([a-z0-9]*) .* $key/i", $input, $namesArray);

                foreach ($namesArray[1] as $item) {
                    $root[$item] = $root[$key] + 1;
                    $input = preg_replace("/$item reposted $key/", '', $input);
                }

                foreach ($root as $n) {
                    if ($n > $max) {
                        $max = $n;
                    }
                }
            }
        }
    }

    echo $max;

<?php

        $dir = fopen("php://stdin", 'r');
        $input = file_get_contents($dir);

    //    $nr = $input[0];
//    $input = '6
//Mike reposted Polycarp
//Max reposted Polycarp
//EveryOne reposted Polycarp
//111 reposted Polycarp
//VkCup reposted Polycarp
//Codeforces reposted Polycarp';

//    $input = explode("\n", $input);
    $nr = 0;
    preg_match('/^[0-9]+/', $input, $nr);
    $nr = (int)$nr[0];

    $root = array('polycarp' => 1);

    $namesArray = null;
    //    for ($i = 1; $i <= $nr; $i++) {
    //        preg_match("/^([a-z0-9]{2,24}) .*polycarp/", strtolower($input[$i]), $namesArray);
    //
    //    }
    //
    //    foreach ($namesArray as $name) {
    //        $root[$name] = $root['polycarp'] + 1;
    //    }

    $index = 1;
    while ($index <= $nr) {
        foreach ($root as $key => $value) {
            if ($value == $index) {

                $namesArray = null;
                preg_match_all("/([a-z0-9]*) .* $key/i", $input, $namesArray);

                foreach ($namesArray[1] as $item) {
                    $root[$item] = $index + 1;
                }
            }
        }
        $index++;
    }

    $max=0;
    foreach ($root as $item) {
        if ($item > $max){
            $max = $item;
        }
    }

    echo $max;

<?php
    //
                $dir = fopen("php://stdin", 'r');
                $input = stream_get_contents($dir);

//    $input = '5
//tourist reposted Polycarp
//Petr reposted Tourist
//WJMZBMR reposted Petr
//sdya reposted wjmzbmr
//vepifanov reposted sdya';

    //    $nr = 0;
    //    preg_match('/^[0-9]+/', $input, $nr);
    //    $nr = (int)$nr[0];

    $arr = explode(PHP_EOL, $input);
    $nr = (int)$arr[0];

    unset($arr[0]);
//    print_r($arr);

    $root = array('polycarp' => 1);

    foreach ($arr as $line) {
        var_dump($line);
        preg_match('/([a-zA-Z0-9]{2,24}) reposted ([a-zA-Z0-9]{2,24})$/', $line, $matches);

//        var_dump($matches);
        $first = strtolower($matches[1]);
        $second = strtolower($matches[2]);
        $root[$first] = $root[$second] + 1;
    }

//    var_dump($root);
    echo max(array_values($root));

<?php
    //
                $dir = fopen("php://stdin", 'r');
                $input = stream_get_contents($dir);

//    $input = '13
//uuuu reposted polycarp
//uuuuuuuuuu reposted uuuu
//uuuuuuuuuuuuuuuuuuuuuuuu reposted uuuuuuuuuu
//vvv reposted uuuuuuuuuuuuuuuuuuuuuuuu
//yyyyyyyyyyyyyyy reposted uuuuuuuuuuuuuuuuuuuuuuuu
//vvvvvvvvvvvvvvvv reposted yyyyyyyyyyyyyyy
//xxxxxxxxxxxxxxxxxxxx reposted uuuuuuuuuu
//uuuuuuuuuuuuuu reposted xxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxx reposted uuuu
//uuuuuuuuuuu reposted vvv
//zzzzzzzzzzzzzzz reposted uuuuuuuuuuu
//wwwwwwww reposted uuuuuuuuuuuuuu
//yyyyyyyyyyyy reposted vvvvvvvvvvvvvvvv';

    //    $nr = 0;
    //    preg_match('/^[0-9]+/', $input, $nr);
    //    $nr = (int)$nr[0];

    $arr = explode(PHP_EOL, $input);
    $nr = (int)$arr[0];

    unset($arr[0]);
    print_r($arr);

    $root = array('polycarp' => 1);

    foreach ($arr as $line) {
        preg_match('/^([a-z0-9]{2,24}) reposted ([a-z0-9]{2,24})$/', $line, $matches);
        $first = strtolower($matches[1]);
        $second = strtolower($matches[2]);
        $root[$first] = $root[$second] + 1;
    }

    var_dump($root);
    echo max(array_values($root));

<?php

        $dir = fopen("php://stdin", 'r');
        $input = stream_get_contents($dir);

//    $input = '5
//tourist reposted Polycarp
//Petr reposted Tourist
//WJMZBMR reposted Petr
//sdya reposted wjmzbmr
//vepifanov reposted sdya';

    $nr = 0;
    preg_match('/^[0-9]+/', $input, $nr);
    $nr = (int)$nr[0];

    $root = array('polycarp' => 1);

    $index = 1;
    while ($index <= $nr) {
        foreach ($root as $key => $value) {
            if ($value == $index) {

                $namesArray = null;
                preg_match_all("/([a-z0-9]*) .* $key/i", $input, $namesArray);

                foreach ($namesArray[1] as $item) {
                    $root[$item] = $index + 1;
                }
            }
        }
        $index++;
    }

    $max=0;
    foreach ($root as $item) {
        if ($item > $max){
            $max = $item;
        }
    }

    echo $max;

<?php

        $dir = fopen("php://stdin", 'r');
        $input = file_get_contents($dir);
        fclose($dir);

    //    $nr = $input[0];
//    $input = '6
//Mike reposted Polycarp
//Max reposted Polycarp
//EveryOne reposted Polycarp
//111 reposted Polycarp
//VkCup reposted Polycarp
//Codeforces reposted Polycarp';

//    $input = explode("\n", $input);
    $nr = 0;
    preg_match('/^[0-9]+/', $input, $nr);
    $nr = (int)$nr[0];

    $root = array('polycarp' => 1);

    $namesArray = null;
    //    for ($i = 1; $i <= $nr; $i++) {
    //        preg_match("/^([a-z0-9]{2,24}) .*polycarp/", strtolower($input[$i]), $namesArray);
    //
    //    }
    //
    //    foreach ($namesArray as $name) {
    //        $root[$name] = $root['polycarp'] + 1;
    //    }

    $index = 1;
    while ($index <= $nr) {
        foreach ($root as $key => $value) {
            if ($value == $index) {

                $namesArray = null;
                preg_match_all("/([a-z0-9]*) .* $key/i", $input, $namesArray);

                foreach ($namesArray[1] as $item) {
                    $root[$item] = $index + 1;
                }
            }
        }
        $index++;
    }

    $max=0;
    foreach ($root as $item) {
        if ($item > $max){
            $max = $item;
        }
    }

    echo $max;

<?php
$countLine = (int)trim(fgets(STDIN));
$arrayWithReported = array();
for ($i = 1; $i <= $countLine+1; $i++) {
    $enterArr[$i] = trim(fgets(STDIN));
    if ($i == 1) {
        $firstValue = explode(" reposted ", $enterArr[$i]);
        $arrayWithReported[] = $firstValue[0];
        $total = $i;
    }
    else{
    $firstValue = explode(" reposted ", $enterArr[$i]);
    $secondValue = explode(" reposted ", $enterArr[$i - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);

        if ($repoFirst == $repoSecond) {
            $total = $i;
        } else {
            $total = $i;
            break;
        }
    } else {
        $total = $i;
        break;
    }
    }
}
echo ($total != 1)?$total:0;
?>

<?php
$countLine= (int)trim(fgets(STDIN));
$enterArr = array();
for($i=0;$i<$countLine;$i++){
$enterArr[$i+1]=trim(fgets(STDIN));
}
foreach($enterArr as $key => $value){
if($key == 1){
$total = $key+1;
continue;
}
$firstValue = explode(" reposted ", $value);
$secondValue = explode(" reposted ", $enterArr[$key - 1]);
$repoFirst = strtolower($firstValue[1]);
$repoSecond = strtolower($secondValue[0]);
if($repoFirst == $repoSecond && (strlen($repoFirst)>1 and strlen($repoFirst)<25) && (strlen($repoSecond)>1 and strlen($repoSecond)<25)){
$total = $key+1;
}
else{
$total = $key;
break;
}
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $firstValue = explode(" reposted ", $value);
        $arrayWithReported[] = $firstValue[0];
        $total = $key + 1;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key + 1;
        } else {
            $total = $key;
            break;
        }
    } else {
        $total = $key;
        break;
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$arrayWithReported = array();
for ($i = 1; $i <= $countLine+1; $i++) {
    $enterArr[$i] = trim(fgets(STDIN));
    if ($i == 1) {
        $firstValue = explode(" reposted ", $enterArr[$i]);
        $arrayWithReported[] = strtolower($firstValue[0]);
        $total = $i;
        if(strtolower($firstValue[1]) != strtolower('Polycarp')){
        break;
        }
    }
    else{
    $firstValue = explode(" reposted ", $enterArr[$i]);
    if ($i == 14) {
            $total = $i;
            break;
    }
    if (!is_numeric(array_search(strtolower($firstValue[0]), $arrayWithReported))) {
        if (is_numeric(array_search(strtolower($firstValue[1]), $arrayWithReported))) {
            $total = $i;
        $arrayWithReported[] = strtolower($firstValue[0]);
        } else {
            $total = $i;
            break;
        }
    } else {
        $total = $i;
        break;
    }
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
if($countLine == 0){
echo 0;}
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $firstValue = explode(" reposted ", $value);
        $arrayWithReported[] = $firstValue[0];
        $total = $key + 1;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key;
        } else {
            $total = $key+1;
            break;
        }
    } else {
        $total = $key;
        break;
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$arrayWithReported = array();
for ($i = 1; $i <= $countLine+1; $i++) {
    $enterArr[$i] = trim(fgets(STDIN));
    if ($i == 1) {
        $firstValue = explode(" reposted ", $enterArr[$i]);
        $arrayWithReported[] = strtolower($firstValue[0]);
        $total = $i;
        if(strtolower($firstValue[1]) != strtolower('Polycarp')){
        break;
        }
    }
    else{
    $firstValue = explode(" reposted ", $enterArr[$i]);
    if (!is_numeric(array_search(strtolower($firstValue[0]), $arrayWithReported))) {
        if (is_numeric(array_search(strtolower($firstValue[1]), $arrayWithReported))) {
            $total = $i;
        $arrayWithReported[] = strtolower($firstValue[0]);
        } else {
            $total = $i;
            break;
        }
    } else {
        $total = $i;
        break;
    }
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $firstValue = explode(" reposted ", $value);
        $arrayWithReported[] = $firstValue[0];
        $total = $key + 1;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key+1;
        } else {
            $total = $key;
            break;
        }
    } else {
        $total = $key;
        break;
    }
}
echo (int)$total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$arrayWithReported = array();
for ($i = 1; $i <= $countLine+1; $i++) {
    $enterArr[$i] = trim(fgets(STDIN));
    if ($i == 1) {
        $firstValue = explode(" reposted ", $enterArr[$i]);
        $arrayWithReported[] = strtolower($firstValue[0]);
        $total = $i;
        if(strtolower($firstValue[1]) != strtolower('Polycarp')){
        break;
        }
    }
    else{
    $firstValue = explode(" reposted ", $enterArr[$i]);
    $secondValue = explode(" reposted ", $enterArr[$i - 1]);
    if (!is_numeric(array_search(strtolower($firstValue[0]), $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);

        if ($repoFirst == $repoSecond) {
            $total = $i;
        } else {
            $total = $i;
            break;
        }
    } else {
        $total = $i;
        break;
    }
    }
}
echo ($total != 1)?$total:0;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
if($countLine == 0){
echo 0; die;}
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $firstValue = explode(" reposted ", $value);
        $arrayWithReported[] = $firstValue[0];
        $total = $key + 1;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key;
        } else {
            $total = $key+1;
            break;
        }
    } else {
        $total = $key;
        break;
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$arrayWithReported = array();
for ($i = 1; $i <= $countLine+1; $i++) {
    $enterArr[$i] = trim(fgets(STDIN));
    if ($i == 1) {
        $firstValue = explode(" reposted ", $enterArr[$i]);
        $arrayWithReported[] = strtolower($firstValue[0]);
        $total = $i;
        if(strtolower($firstValue[1]) != strtolower('Polycarp')){
        break;
        }
    }
    else{
    $firstValue = explode(" reposted ", $enterArr[$i]);
    $secondValue = explode(" reposted ", $enterArr[$i - 1]);
    if (!is_numeric(array_search(strtolower($firstValue[0]), $arrayWithReported))) {
        $arrayWithReported[] = strtolower($firstValue[0]);
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);

        if ($repoFirst == $repoSecond) {
            $total = $i;
        } else {
            $total = $i;
            break;
        }
    } else {
        $total = $i;
        break;
    }
    }
}
echo ($total != 1)?$total:0;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$arrayWithReported = array();
for ($i = 1; $i <= $countLine+1; $i++) {
    $enterArr[$i] = trim(fgets(STDIN));
    if ($i == 1) {
        $firstValue = explode(" reposted ", $enterArr[$i]);
        $arrayWithReported[] = strtolower($firstValue[0]);
        $total = $i;
        if(strtolower($firstValue[1]) != strtolower('Polycarp')){
        break;
        }
    }
    else{
    $firstValue = explode(" reposted ", $enterArr[$i]);
    if ($i > 12) {
    var_dump($i);
    var_dump($firstValue);
    }
    if (!is_numeric(array_search(strtolower($firstValue[0]), $arrayWithReported))) {
        if (is_numeric(array_search(strtolower($firstValue[1]), $arrayWithReported))) {
            $total = $i;
        $arrayWithReported[] = strtolower($firstValue[0]);
        } else {
            $total = $i;
            break;
        }
    } else {
        $total = $i;
        break;
    }
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$arrayWithReported = array(strtolower('Polycarp'));
$total = $arrayWithReported;
for ($i = 1; $i <= $countLine+1; $i++) {
    $enterArr[$i] = trim(fgets(STDIN));
    if ($i == 1) {
        $firstValue = explode(" reposted ", $enterArr[$i]);
        $repoValue = strtolower($firstValue[1]);
        $arrayWithReported[] = strtolower($firstValue[0]);
        if (!is_numeric(array_search($repoValue, $total))) {
        $total[] = $repoValue;
        }
    }
    else{
    $firstValue = explode(" reposted ", $enterArr[$i]);
    $repoValue = strtolower($firstValue[1]);
        if (is_numeric(array_search($repoValue, $arrayWithReported))) {
        $arrayWithReported[] = strtolower($firstValue[0]);
        if (!is_numeric(array_search($repoValue, $total))) {
        $total[] = $repoValue;
        }
        } else {
            break;
        }
    }
}
echo count($total)+1;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$arrayWithReported = array();
for ($i = 1; $i <= $countLine+1; $i++) {
    $enterArr[$i] = trim(fgets(STDIN));
    if ($i == 1) {
        $firstValue = explode(" reposted ", $enterArr[$i]);
        $arrayWithReported[] = strtolower($firstValue[0]);
        $total = $i;
        if(strtolower($firstValue[1]) != strtolower('Polycarp')){
        break;
        }
    }
    else{
    $firstValue = explode(" reposted ", $enterArr[$i]);
    $secondValue = explode(" reposted ", $enterArr[$i - 1]);
    if (!is_numeric(array_search(strtolower($firstValue[0]), $arrayWithReported))) {
        $arrayWithReported[] = strtolower($firstValue[0]);
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);

        if ($repoFirst == $repoSecond) {
            $total = $i;
        } else {
            $total = $i;
            break;
        }
    } else {
        $total = $i;
        break;
    }
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $firstValue = explode(" reposted ", $value);
        $arrayWithReported[] = $firstValue[0];
        $total = $key + 2;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key+1;
        } else {
            $total = $key+1;
            break;
        }
    } else {
        $total = $key+1;
        break;
    }
}
echo (int)$total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
if($countLine == 0){
echo 0;}
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $firstValue = explode(" reposted ", $value);
        $arrayWithReported[] = $firstValue[0];
        $total = $key + 1;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key;
        } else {
            $total = $key;
            break;
        }
    } else {
        $total = $key;
        break;
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $total = $key + 1;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!array_search($repoSecond, $arrayWithReported)) {
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key + 1;
        } else {
            $total = $key;
            break;
        }
    } else {
        $total = $key;
        break;
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $firstValue = explode(" reposted ", $value);
        $arrayWithReported[] = $firstValue[0];
        $total = $key + 1;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key;
        } else {
            $total = $key;
            break;
        }
    } else {
        $total = $key;
        break;
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$arrayWithReported = array();
for ($i = 1; $i <= $countLine+1; $i++) {
    $enterArr[$i] = trim(fgets(STDIN));
    if ($i == 1) {
        $firstValue = explode(" reposted ", $enterArr[$i]);
        $arrayWithReported[] = $firstValue[0];
        $total = $i;
    }
    else{
    $firstValue = explode(" reposted ", $enterArr[$i]);
    $secondValue = explode(" reposted ", $enterArr[$i - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);

        if ($repoFirst == $repoSecond) {
            $total = $i;
        } else {
            $total = $i;
            break;
        }
    } else {
        $total = $i;
        break;
    }
    }
}
echo (int)$total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $total = $key + 1;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!array_search($firstValue, $arrayWithReported)) {
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key + 1;
        } else {
            $total = $key;
            break;
        }
    } else {
        $total = $key;
        break;
    }
}
echo $total;
?>

<?php
$countLine = (int)trim(fgets(STDIN));
$enterArr = array();
for ($i = 0; $i < $countLine; $i++) {
    $enterArr[$i + 1] = trim(fgets(STDIN));
}
$arrayWithReported = array();
foreach ($enterArr as $key => $value) {
    if ($key == 1) {
        $firstValue = explode(" reposted ", $value);
        $arrayWithReported[] = $firstValue[0];
        $total = $key + 1;
        continue;
    }
    $firstValue = explode(" reposted ", $value);
    $secondValue = explode(" reposted ", $enterArr[$key - 1]);
    if (!is_numeric(array_search($firstValue[0], $arrayWithReported))) {
        $arrayWithReported[] = $firstValue[0];
        $repoFirst = strtolower($firstValue[1]);
        $repoSecond = strtolower($secondValue[0]);
        if ($repoFirst == $repoSecond && (strlen($repoFirst) > 1 and strlen($repoFirst) < 25) && (strlen($repoSecond) > 1 and strlen($repoSecond) < 25)) {
            $total = $key+1;
        } else {
            $total = $key;
            break;
        }
    } else {
        $total = $key;
        break;
    }
}
echo $total;
?>


A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 ≤ i ≤ n) (n is the permutation size) the following equations hold ppi = i and pi ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.

A single line contains a single integer n (1 ≤ n ≤ 100) — the permutation size.

If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn — permutation p, that is perfect. Separate printed numbers by whitespaces.

<?php
$a = range(1, trim(fgets(STDIN)));
if(count($a) % 2 == 0)
{
    $b = implode(" ", array_reverse($a));
    print $b;
}
else
{
    print "-1";
}
?>

<?php

error_reporting(0);

solve();

function solve(){

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

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

	if ($N % 2 === 1) print(-1);
	else
	{
		for ($i = 1; $i <= intval($N / 2); $i++)
		{
			print($i * 2);
			print(" ");
			print($i * 2 - 1);
			print(" ");
		}
	}

	$Input->close();
}

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
$a = range(1, trim(fgets(STDIN)));
if(count($a) == 1)
{
    print "-1";
}
elseif(count($a) % 2 == 0)
{
    $b = implode(" ", array_reverse($a));
    print $b;
}
else
{
    $b = array_reverse($a);
    $c = $b[0];
    $b[0] = $b[floor(count($b) / 2)];
    $b[floor(count($b) / 2)] = $c;
    $d = implode(" ", $b);
    print $d;
}
?>