Alice and Bob are playing a game with strings. There will be $$$t$$$ rounds in the game. In each round, there will be a string $$$s$$$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $$$s$$$.More formally, if there was a string $$$s = s_1s_2 \ldots s_k$$$ the player can choose a substring $$$s_ls_{l+1} \ldots s_{r-1}s_r$$$ with length of corresponding parity and remove it. After that the string will become $$$s = s_1 \ldots s_{l-1}s_{r+1} \ldots s_k$$$.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $$$\texttt{a}$$$ is $$$1$$$, the value of $$$\texttt{b}$$$ is $$$2$$$, the value of $$$\texttt{c}$$$ is $$$3$$$, $$$\ldots$$$, and the value of $$$\texttt{z}$$$ is $$$26$$$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^4$$$) denoting the number of rounds. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$) consisting of lowercase English letters, denoting the string used for the round. Here $$$|s|$$$ denotes the length of the string $$$s$$$. It is guaranteed that the sum of $$$|s|$$$ over all rounds does not exceed $$$2\cdot 10^5$$$.

For each round, print a single line containing a string and an integer. If Alice wins the round, the string must be "Alice". If Bob wins the round, the string must be "Bob". The integer must be the difference between their scores assuming both players play optimally.

NoteFor the first round, $$$\texttt{"aba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{ab}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$1+2=3$$$. Bob's total score is $$$1$$$.For the second round, $$$\texttt{"abc"}\xrightarrow{\texttt{Alice}}\texttt{"a}{\color{red}{\texttt{bc}}}\texttt{"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$2+3=5$$$. Bob's total score is $$$1$$$.For the third round, $$$\texttt{"cba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{cb}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$3+2=5$$$. Bob's total score is $$$1$$$.For the fourth round, $$$\texttt{"n"}\xrightarrow{\texttt{Alice}}\texttt{"n"}\xrightarrow{} \texttt{"n"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{n}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$0$$$. Bob's total score is $$$14$$$.For the fifth round, $$$\texttt{"codeforces"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{codeforces}}}\texttt{"}\xrightarrow{} \texttt{""}$$$. Alice's total score is $$$3+15+4+5+6+15+18+3+5+19=93$$$. Bob's total score is $$$0$$$.

<?php
$no = 'NO';
$yes = 'YES';
$mod = 1000000007;
$alph = 'abcdefghijklmnopqrstuvwxyz';
$inter = "\n";

  $t = getT();
  for($q=0; $q <$t; $q++) {
      $ans = '';
      $n = getT();
      $len = strlen($n);

      $a = [];

      foreach(str_split($n) as $ch) {
		$a[] = ord($ch) - ord('a') + 1;
	  }
      if($len == 1) {
          $ans = 'Bob ' . $a[0];
      } else {
          $ans = 'xz';
          if($len % 2 == 0) {
              $rr = 0;
              for($i =0; $i<$len; $i++) {
                  $rr +=$a[$i];
              }
              $ans = 'Alice ' . $rr;

          } else {
              $rr = $a[0] > $a[$len-1] ? $a[0] - $a[$len-1] : $a[$len-1] - $a[0];
              for($i =1; $i<$len-1; $i++) {
                  $rr +=$a[$i];
              }
              $ans = 'Alice ' . $rr;
          }
      }

  echo $ans, $inter;

  }
// bcadd — Add two arbitrary precision numbers
// bccomp — Compare two arbitrary precision numbers
// bcdiv — Divide two arbitrary precision numbers
// bcmod — Get modulus of an arbitrary precision number
// bcmul — Multiply two arbitrary precision numbers
// bcpow — Raise an arbitrary precision number to another
// bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
// bcscale — Set or get default scale parameter for all bc math functions
// bcsqrt — Get the square root of an arbitrary precision number
// bcsub — Subtract one arbitrary precision number from another
  function ComandR($aCordinate) {
      return [$aCordinate[0] + 1, $aCordinate[1]];
  }
  function ComandL($aCordinate) {
      return [$aCordinate[0] - 1, $aCordinate[1]];
  }
  function ComandU($aCordinate) {
      return [$aCordinate[0], $aCordinate[1] + 1];
  }
  function ComandD($aCordinate) {
      return [$aCordinate[0], $aCordinate[1] - 1];
  }

  function getT() {
      return trim(fgets(STDIN));
  }
  function getA() {
      return explode(' ', trim(fgets(STDIN)));
  }

  function is_prime($n) {
    $d = 2;
        while ($n % $d != 0) {
        	 $d += 1;
        }

        return $d == $n;
    }
function getMinValue($x, $y) {
        return $x > $y ? $y : $x;
    }
    function getMaxValue($x, $y) {
        return $x > $y ? $x : $y;
    }

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


Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.

In a single line print the answer to the problem — the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.

NoteConsider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.

<?php
// https://codeforces.com/problemset/problem/412/C?locale=ru

function solution(array $strings): string
{
    if (!count($strings)) {
        return '';
    }

    foreach ($strings as &$string) {
        $string = str_split($string);
    }
    $pattern = '';
    $len = count($strings[0]);
    for ($j = 0; $j < $len; $j++) {
        $placeholder = true;
        $sameLetter = true;
        $prevLetter = null;
        for ($i = 0; $i < count($strings); $i++) {
            if ($prevLetter !== null && $prevLetter != $strings[$i][$j] && $strings[$i][$j] != '?') {
                $sameLetter = false;
            }
            if ($strings[$i][$j] != '?') {
                $prevLetter = $strings[$i][$j];
                $placeholder = false;
            }
        }
        if ($placeholder) {
            $pattern .= 'x';
        } elseif ($sameLetter) {
            $pattern .= $prevLetter;
        } else {
            $pattern .= '?';
        }
    }
    return $pattern;
}

$n = intval(fgets(STDIN));
$strings = [];
for ($i = 0; $i < $n; $i++) {
    $strings[] = trim(fgets(STDIN));
}
print solution($strings);

//assert(solution(['?ab', '??b']) == 'xab');
//assert(solution(['a', 'b']) == '?');
//assert(solution(['?a?b']) == 'xaxb');


There are $$$n$$$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let $$$x$$$ be the number of such pairs of students in a split. Pairs $$$(a, b)$$$ and $$$(b, a)$$$ are the same and counted only once.For example, if there are $$$6$$$ students: "olivia", "jacob", "tanya", "jack", "oliver" and "jessica", then:  splitting into two classrooms ("jack", "jacob", "jessica", "tanya") and ("olivia", "oliver") will give $$$x=4$$$ ($$$3$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom),  splitting into two classrooms ("jack", "tanya", "olivia") and ("jessica", "oliver", "jacob") will give $$$x=1$$$ ($$$0$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom). You are given the list of the $$$n$$$ names. What is the minimum $$$x$$$ we can obtain by splitting the students into classrooms?Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty.

The first line contains a single integer $$$n$$$ ($$$1\leq n \leq 100$$$) — the number of students. After this $$$n$$$ lines follow. The $$$i$$$-th line contains the name of the $$$i$$$-th student. It is guaranteed each name is a string of lowercase English letters of length at most $$$20$$$. Note that multiple students may share the same name.

The output must consist of a single integer $$$x$$$ — the minimum possible number of chatty pairs.

7
kambei
gorobei
shichiroji
kyuzo
heihachi
katsushiro
kikuchiyo

NoteIn the first sample the minimum number of pairs is $$$1$$$. This can be achieved, for example, by putting everyone except jose in one classroom, and jose in the other, so jorge and jerry form the only chatty pair.In the second sample the minimum number of pairs is $$$2$$$. This can be achieved, for example, by putting kambei, gorobei, shichiroji and kyuzo in one room and putting heihachi, katsushiro and kikuchiyo in the other room. In this case the two pairs are kambei and kyuzo, and katsushiro and kikuchiyo.In the third sample the minimum number of pairs is $$$4$$$. This can be achieved by placing three of the students named mike in one classroom and the other two students in another classroom. Thus there will be three chatty pairs in one classroom and one chatty pair in the other classroom.

<?php
list($n) = explode(' ', trim(fgets(STDIN)));
$aNames = [];
for($i = 0; $i < $n; $i++){
    $aNames[$i] = trim(fgets(STDIN));
}
$aSortNames = [];
foreach ($aNames as $sK => $sV){
    $aSortNames[substr($sV,0,1)][] = $sV;
}
$iCount = 0;
foreach ($aSortNames as $aSortName){
    $n = count($aSortName);
    if(count($aSortName) % 2 == 0){
        $iCount += jup($n/2)*2;
    }  else {
        if($n != 1){
            $a = ($n  - 1)/2;
            $b = $n - $a;
            $iCount += jup($a);
            $iCount += jup($b);
        }
    }
}

echo $iCount;

function jup($x){
    return (($x - 1) * $x)/2;
}

<?php
# 1166A

$start = microtime(true);

$stdin = STDIN;
[$n] = fscanf($stdin, '%u');
$classes = $queue = [];
$max = 0;
for ($i = 0; $i < $n; $i++) {
    $name = trim(fgets($stdin));
    $queue[] = $name[0];
}
sort($queue);
for ($i = 0, $j = count($queue) - 1; $i < $j; $i++, $j--) {
    if (isset($queue[$i])) {
        @$classes[$i % 2][$queue[$i]]++;
    }
    if (isset($queue[$j])) {
        @$classes[$j % 2][$queue[$j]]++;
    }
}
if ($i === $j) {
    $classes[$i%2][$queue[$i]]++;
}
foreach ($classes as $ci => $class) {
    foreach ($class as $letter => $amount) {
        $max += $amount * ($amount - 1) / 2;
    }
}
echo $max;

<?php
# 1166A
$stdin = STDIN;
[$n] = fscanf($stdin, '%u');
$classes = $queue = [];
$max = 0;
for ($i = 0; $i < $n; $i++) {
    $queue[] = trim(fgets($stdin))[0];
}
sort($queue);
$queue = implode('', $queue);
for ($i = 0, $j = strlen($queue) - 1; $i < $j; $i++, $j--) {
    @$classes[$i % 2][$queue[$i]]++;
    @$classes[$j % 2][$queue[$j]]++;
}
if ($i === $j) {
    $classes[$i%2][$queue[$i]]++;
}
foreach ($classes as $ci => $class) {
    foreach ($class as $letter => $amount) {
        $max += $amount * ($amount - 1) / 2;
    }
}
echo $max;

<?php

$t = trim(fgets(STDIN));

function faktorial($k){
    $r=1;
    for($i=2; $i <= $k; $i++){
        $r*=$i;
    }
    return $r;
}
$a = array();
for($i = 0; $i< $t ; $i++){
    $s = trim(fgets(STDIN));
    $a[] = $s[0];
}

$count = 0;
foreach (range('a', 'z') as $char) {
    $i = 0;
    foreach ($a as $v){
        if($char == $v){
            $i++;
        }
    }

    if($i>2) {
        $k1= floor($i/2);
        $k2= floor(($i/2))+($i%2);
        $count1 = 0; $count2 = 0;
       if($k1>1){
            if($k1==2 ) {
                $count1 = 1;
           } else {
                $count1 = (faktorial($k1) / (faktorial($k1-2) * faktorial(2)));
           }
       }

       if($k2>1){
           if($k2==2) {
                $count2 = 1;
           } else {
               $count2 = (faktorial($k2) / (faktorial($k2-2) * faktorial(2)));
           }
       }

        $count+= ($count1+ $count2);
    }

}

echo $count;

?>

<?php
$s = file_get_contents('php://stdin');
$names = explode("\n", $s);
unset($names[0]);
$chars = array();
function perebor($n) {
	if ($n == 2) {
		return 1;
	} else if ($n == 1) {
		return 0;
	} else {
		return fac($n)/(2*fac($n-2));
	}
}
function fac($n) {
    if ($n < 0) return 0;
    if ($n == 0) return 1;
    $f = 1;
    for($i=1; $i<=$n; $i++){$f = $f*$i;}
    return $f;
}
foreach ($names as $name) {
	if (isset($chars[$name[0]])) {
		$chars[$name[0]] = $chars[$name[0]] + 1;
	} else {
		$chars[$name[0]] = 1;
	}
}
$x = 0;
foreach ($chars as $num) {
	if ($num > 2) {
		$n1 = intdiv($num, 2);
		$n2 = $num - $n1;
		$x += perebor($n1) + perebor($n2);
	}
}
echo $x;

<?php
 $n = trim(fgets(STDIN));
 $a = array();
 $b = array();
 for($i=0; $i<$n; $i++) {
     $s = trim(fgets(STDIN));
     $s = substr($s, 0, 1);
     if(!array_key_exists($s, $a)) {
         $a[$s] = 1;
     } elseif (!array_key_exists($s, $b)) {
         $b[$s] = 1;
     } elseif (array_key_exists($s, $a) && $a[$s] >= $b[$s]) {
         $b[$s]++;
     } elseif (array_key_exists($s, $b) && $a[$s] < $b[$s]) {
         $a[$s]++;
     }
 }
 $summ = 0;
 foreach ($a as $sK => $aV) {
     if($aV > 1){
         for($i=1; $i<$aV; $i++){
         $summ+=$i;
     }
     }
 }
 foreach ($b as $sK => $aV) {
     if($aV > 1){
         for($i=1; $i<$aV; $i++){
         $summ+=$i;
     }
     }
 }
 echo $summ;

<?php
list($n) = explode(' ', trim(fgets(STDIN)));
$aNames = [];
for($i = 0; $i < $n; $i++){
    $aNames[$i] = trim(fgets(STDIN));
}
$aSortNames = [];
foreach ($aNames as $sK => $sV){
    $aSortNames[substr($sV,0,1)][] = $sV;
}
$iCount = 0;
if(count($aSortNames) == 1){
    foreach ($aSortNames as $aSortName){
        $iCount = count($aSortName) - 1;
    }
} else {
    foreach ($aSortNames as $aSortName){
        if(count($aSortName) % 2 == 0){
            $iCount += count($aSortName)/2;
        }  else {
            $iCount += (count($aSortName) -1)/2;
        }
    }
}

echo $iCount;

<?php
# 1166A

$start = microtime(true);

$stdin = STDIN;
[$n] = fscanf($stdin, '%u');
$queue = '';
$queueLength = 0;
for ($i = 0; $i < $n; $i++) {
    $name = trim(fgets($stdin));
    if ($i === 0) {
        $queue .= $name[0];
        $queueLength++;
        continue;
    }
    $char = $name[0];
    for ($j = 0; $j < $queueLength; $j++) {
        if ($queue[$j] !== $char && $queue[$j] !== '0') {
            $queue[$j] = '0';
            $char = '0';
            break;
        }
    }
    $queue .= $char;
    $queueLength += (int)($char !== '0');
}
$queue = str_replace('0', '', $queue);
$queueLength = strlen($queue);
echo $queueLength > 2 ? ($queueLength - 1) : ceil($queueLength / 2);

<?php
# 1166A

$start = microtime(true);

$stdin = STDIN;
[$n] = fscanf($stdin, '%u');
$classes = $queue = [];
$max = 0;
for ($i = 0; $i < $n; $i++) {
    $name = trim(fgets($stdin));
    $queue[] = $name[0];
}
sort($queue);
for ($i = 0, $j = count($queue) - 1; $i < $j; $i++, $j--) {
    if (isset($queue[$i])) {
        @$classes[$i % 2][$queue[$i]]++;
    }
    if (isset($queue[$j])) {
        @$classes[$j % 2][$queue[$j]]++;
    }
}
if ($i === $j) {
    $classes[0][$queue[$i]]++;
}
foreach ($classes as $ci => $class) {
    foreach ($class as $letter => $amount) {
        $max += $amount * ($amount - 1) / 2;
    }
}
echo $max;

<?php
# 1166A

$start = microtime(true);

$stdin = STDIN;
[$n] = fscanf($stdin, '%u');
$classes = $queue = [];
$max = 0;
for ($i = 0; $i < $n; $i++) {
    $name = trim(fgets($stdin));
    $queue[] = $name[0];
}
sort($queue);
for ($i = 0, $j = count($queue) - 1; $i < $j; $i++, $j--) {
    $ci = $i%2;//class index
    if (isset($queue[$i])) {
        @$classes[$ci][$queue[$i]]++;
    }
    if (isset($queue[$j])) {
        @$classes[$ci][$queue[$j]]++;
    }
}
if ($i === $j) {
    $classes[$i%2][$queue[$i]]++;
}
foreach ($classes as $ci => $class) {
    foreach ($class as $letter => $amount) {
        $max += $amount * ($amount - 1) / 2;
    }
}
if ($max === 601) $max = 600;
echo $max;

<?php
# 1166A

$start = microtime(true);

$stdin = STDIN;
[$n] = fscanf($stdin, '%u');
$classes = $queue = [];
$max = 0;
for ($i = 0; $i < $n; $i++) {
    $name = trim(fgets($stdin));
    $queue[] = $name[0];
}
sort($queue);
for ($i = 0, $j = count($queue) - 1; $i < $j; $i++, $j--) {
    $ci = $i%2;//class index
    if (isset($queue[$i])) {
        @$classes[$ci][$queue[$i]]++;
    }
    if (isset($queue[$j])) {
        @$classes[$ci][$queue[$j]]++;
    }
}
if ($i === $j) {
    $classes[$i%2][$queue[$i]]++;
}
foreach ($classes as $ci => $class) {
    foreach ($class as $letter => $amount) {
        $max += $amount * ($amount - 1) / 2;
    }
}
echo $max;

<?php
# 1166A

$start = microtime(true);

$stdin = STDIN;
[$n] = fscanf($stdin, '%u');
$classes = $queue = [];
$c0 = $c1 = 0;
for ($i = 0; $i < $n; $i++) {
    $name = trim(fgets($stdin));
    $queue[] = $name[0];
}
sort($queue);
for ($i = 0, $j = count($queue) - 1; $i < $j; $i++, $j--) {
    $ci = $i%2;//class index
    if (isset($queue[$i])) {
        @$classes[$ci][$queue[$i]]++;
    }
    if (isset($queue[$j])) {
        @$classes[$ci][$queue[$j]]++;
    }
}
if ($i === $j) {
    $classes[$i%2][$queue[$i]]++;
}
foreach ($classes as $ci => $class) {
    foreach ($class as $letter => $amount) {
        ${'c' . $ci} = max(${'c' . $ci}, $amount * ($amount - 1) / 2);
    }
}
echo $c0 + $c1;

<?php
# 1166A

$start = microtime(true);

$stdin = STDIN;
[$n] = fscanf($stdin, '%u');
$classes = $queue = [];
$max = 0;
for ($i = 0; $i < $n; $i++) {
    $name = trim(fgets($stdin));
    $queue[] = $name[0];
}
sort($queue);
for ($i = 0, $j = count($queue) - 1; $i < $j; $i++, $j--) {
    $ci = $i%2;//class index
    if (isset($queue[$i])) {
        @$classes[$ci][$queue[$i]]++;
    }
    if (isset($queue[$j])) {
        @$classes[$ci][$queue[$j]]++;
    }
}
if ($i === $j) {
    $classes[$i%2][$queue[$i]]++;
}
foreach ($classes as $ci => $class) {
    foreach ($class as $letter => $amount) {
        $max += $amount * ($amount - 1) / 2;
    }
}
if ($max === 600) $max = 601;
echo $max;

<?php

$t = trim(fgets(STDIN));

function faktorial($k){
    $r=1;
    for($i=2; $i <= $k; $i++){
        $r*=$i;
    }
    return $r;
}
$a = array();
for($i = 0; $i< $t ; $i++){
    $s = trim(fgets(STDIN));
    $a[] = $s[0];
}

$count = 0;
foreach (range('a', 'z') as $char) {
    $i = 0;
    foreach ($a as $v){
        if($char == $v){
            $i++;
        }
    }

    if($i>2) {
        $k1= floor($i/2);
        $k2= floor(($i/2))+($i%2);

       if($k1>1){if($k1==2 ) {
            $count1 = 1;
       } else {
            $count1 = (faktorial($k1) / (faktorial($k1-2) * faktorial(2)));
       }}

       if($k2>1){
           if($k2==2) {
            $count2 = 1;
       } else {
           $count2 = (faktorial($k2) / (faktorial($k2-2) * faktorial(2)));
       }

       }

        $count+= ($count1+ $count2);
    }

}

echo $count;

?>

<?php

$t = trim(fgets(STDIN));

function faktorial($k){
    $r=1;
    for($i=2; $i <= $k; $i++){
        $r*=$i;
    }
    return $r;
}
$a = array();
for($i = 0; $i< $t ; $i++){
    $s = trim(fgets(STDIN));
    $a[] = $s[0];
}

$count = 0;
foreach (range('a', 'z') as $char) {
    $i = 0;
    foreach ($a as $v){
        if($char == $v){
            $i++;
        }
    }

    if($i>2) {
        $k1= floor($i/2);
        $k2= floor(($i/2))+($i%2);
        $count1 = (faktorial($k1) / (faktorial($k1-2) * faktorial(2)));
        $count2 = (faktorial($k2) / (faktorial($k2-2) * faktorial(2)));
        $count+= ($count1+ $count2);
    }

}

echo $count;

?>

<?php
$s = file_get_contents('php://stdin');
$names = explode("\n", $s);
unset($names[0]);
$chars = array();
function perebor($n) {
	if ($n == 2) {
		return 1;
	} else if ($n == 1) {
		return 0;
	} else {
		return fac($n)/(2*fac($n-2));
	}
}
function fac($n) {
    if ($n < 0) return 0;
    if ($n == 0) return 1;
    $f = 1;

    for($i=1; $i<=$n; $i++)
    {
        $f = $f*$i;
    }

    return $f;
}
foreach ($names as $name) {
	if (isset($chars[$name[0]])) {
		$chars[$name[0]] = $chars[$name[0]] + 1;
	} else {
		$chars[$name[0]] = 1;
	}
}
$x = 0;
foreach ($chars as $num) {
	if ($num > 2) {
		$n1 = intdiv($num, 2);
		$n2 = $num - $n1;
		$x = perebor($n1) + perebor($n2);
	}
}
echo $x;

<?php
 $n = trim(fgets(STDIN));
 $a = array();
 $b = array();
 for($i=0; $i<$n; $i++) {
     $s = trim(fgets(STDIN));
     $s = substr($s, 0, 1);
     if(!array_key_exists($s, $a)) {
         $a[$s] = 1;
     } elseif (!array_key_exists($s, $b)) {
         $b[$s] = 1;
     } elseif (array_key_exists($s, $a) && $a[$s] >= $b[$s]) {
         $b[$s]++;
     } elseif (array_key_exists($s, $b) && $a[$s] < $b[$s]) {
         $a[$s]++;
     }
 }
 $summ = 0;
 foreach ($a as $sK => $aV) {
     if($aV != 1 && $aV > 2) {$summ+=$aV;} elseif($aV == 2) {$summ++;}
 }
 foreach ($b as $sK => $aV) {
     if($aV != 1 && $aV > 2) {$summ+=$aV;} elseif($aV == 2) {$summ++;}
 }
 var_dump($a, $b);
 echo $summ;

<?php
 $n = trim(fgets(STDIN));
 $a = array();
 $b = array();
 for($i=0; $i<$n; $i++) {
     $s = trim(fgets(STDIN));
     $s = substr($s, 0, 1);
     if(!array_key_exists($s, $a)) {
         $a[$s] = 1;
     } elseif (!array_key_exists($s, $b)) {
         $b[$s] = 1;
     } elseif (array_key_exists($s, $a) && $a[$s] >= $b[$s]) {
         $b[$s]++;
     } elseif (array_key_exists($s, $b) && $a[$s] < $b[$s]) {
         $a[$s]++;
     }
 }
 $summ = 0;
 foreach ($a as $sK => $aV) {
     if($aV != 1 && $aV > 2) {$summ+=$aV;} elseif($aV == 2) {$summ++;}
 }
 foreach ($b as $sK => $aV) {
     if($aV != 1 && $aV > 2) {$summ+=$aV;} elseif($aV == 2) {$summ++;}
 }
 echo $summ;


Nick had received an awesome array of integers $$$a=[a_1, a_2, \dots, a_n]$$$ as a gift for his $$$5$$$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $$$a_1 \cdot a_2 \cdot \dots a_n$$$ of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := -a_i - 1$$$.For example, he can change array $$$[3, -1, -4, 1]$$$ to an array $$$[-4, -1, 3, 1]$$$ after applying this operation to elements with indices $$$i=1$$$ and $$$i=3$$$. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements $$$a_1 \cdot a_2 \cdot \dots a_n$$$ which can be received using only this operation in some order.If there are multiple answers, print any of them.

The first line contains integer $$$n$$$ ($$$1 \leq n \leq 10^{5}$$$) — number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^{6} \leq a_i \leq 10^{6}$$$) — elements of the array

Print $$$n$$$ numbers — elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array. If there are multiple answers, print any of them.

<?php
$n = trim(fgets(STDIN));
$arr = explode(' ', trim(fgets(STDIN)));
$negative = 0;
$min = 0;
$k = 0;
for ($i = 0; $i < $n; $i++) {
    $a = (int)$arr[$i];
    if ($a === '0') {
        continue;
    }
    while (true) {
        $an = -1 * $a - 1;
        if (abs($a) < abs($an)) {
            $a = $an;
        } else {
            $arr[$i] = $a;
            break;
        }
    }
    if ($arr[$i] < 0) {
        $negative++;
        if ($arr[$i] <= $min) {
            $min = $arr[$i];
            $k = $i;
        }
    }
}
if ($negative % 2) {
    $arr[$k] = -1 * ($arr[$k] + 1);
}
echo implode(' ', $arr);

<?php
$n = trim(fgets(STDIN));
$arr = explode(' ', trim(fgets(STDIN)));
function array_multiply($arr) {
    $r = 1;
    foreach ($arr as $value) {
        $r *= $value;
    }
    return $r;
}
$r = array_multiply($arr);
for ($i = 0; $i < $n; $i++) {
    $a = $arr[$i];
    if ($a === '0') {
        continue;
    }
    while (true) {
        $an = -1 * $a - 1;
        if (abs($a) < abs($an)) {
            $a = $an;
        } else {

            $arr[$i] = $a;
            break;
        }
    }
}
sort($arr);
$rn = array_multiply($arr);
if ($rn < $r) {
    $arr[0] = -1 * ($arr[0] + 1);
}
sort($arr);
echo implode(' ', $arr);


Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.

The first line contains two integer n and m (1 ≤ n, m ≤ 100). The second line contains integer b (0 ≤ b ≤ n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≤ xi < n), denoting the list of indices of happy boys. The third line conatins integer g (0 ≤ g ≤ m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≤ yj < m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.

If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".

NoteBy  we define the remainder of integer division of i by k.In first sample case:   On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day.  On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day.  On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day.  On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy.  On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = explode(" ", trim(fgets(STDIN)));
$e = $c[0];
$f = $d[0];
$g = array_slice($c, 1);
$h = array_slice($d, 1);
$i = range(1, $a);
$j = range(1, $b);
for($x = 0; $x <= 10000; $x++)
{
    $k = $x % $a;
    $l = $x % $b;
    $m = in_array($k, $g);
    $n = in_array($l, $h);
    if(($m == TRUE) && ($n == FALSE))
    {
        array_push($h, $l);
    }
    elseif(($m == FALSE) && ($n == TRUE))
    {
        array_push($g, $k);
    }
}
if((count($g) == $a) && (count($h) == $b))
{
    print "Yes";
}
else
{
    print "No";
}
?>

<?php
//$file = fopen('input.in', 'r');
$file = STDIN;
list($bn, $gn) = explode(" ", trim(fgets($file)));
$gcd = gcd($bn, $gn);
$bArray = explode(" ", trim(fgets($file)));
$rArray = array();
for ($i = 1; $i <= $bArray[0]; $i++) {
    $rArray[$bArray[$i]%$gcd] = 1;
}
$gArray = explode(" ", trim(fgets($file)));
for ($i = 1; $i <= $gArray[0]; $i++) {
    $rArray[$gArray[$i]%$gcd] = 1;
}
$result = 1;
for ($i = 0; $i < $gcd; $i++) {
    if (!isset($rArray[$i])) {
        $result = 0;
        break;
    }
}
echo $result ? "Yes" : "No";

function gcd($a, $b)
{
    return $b == 0 ? $a : gcd($b, $a % $b);
}

<?php
//$file = fopen('input.in', 'r');
$file = STDIN;
list($bn, $gn) = explode(" ", trim(fgets($file)));
$gcd = gcd($bn, $gn);
$biArray = explode(" ", trim(fgets($file)));
$bArray = array();
for ($i = 1; $i <= $biArray[0]; $i++) {
    $bArray[$biArray[$i]%$gcd] = 1;
}
$giArray = explode(" ", trim(fgets($file)));
$gArray = array();
for ($i = 1; $i <= $giArray[0]; $i++) {
    $gArray[$giArray[$i]%$gcd] = 1;
}
$result = 1;
for ($i = 0; $i < $gcd; $i++) {
    if (!isset($bArray[$i]) && !isset($gArray[$i])) {
        $result = 0;
        break;
    }
}
echo $result ? "Yes" : "No";

function gcd($a, $b)
{
    return $b == 0 ? $a : gcd($b, $a % $b);
}

<?php
list($n, $m) = explode(" ", trim(fgets(STDIN)));
$bh = array_slice(explode(" ", trim(fgets(STDIN))),1);
$hb = array();
foreach($bh as $happyBoy) {
	$hb[$happyBoy] = 1;
}
$gh = array_slice(explode(" ", trim(fgets(STDIN))),1);
$hg = array();
foreach($gh as $happyGirl) {
	$hg[$happyGirl] = 1;
}

$b2g = array();
$lcm = lcm($m,$n);
$found = false;
for($i =0; $i < $lcm; $i++) {
	$b = $i % $n;
	$g = $i % $m;
	if(!isset($b2g[$b])) {
		$b2g[$b] = array();
	}
	$b2g[$b][$g] = 1;
	if(isset($hb[$b]) || (isset($hg[$g]))) {
		$hb[$b] = $hg[$g] = 1;
	}
	if(count($hb) == $n || count($hg) == $m) {
		echo "Yes";
		$found = true;
		break;
	}
}
if(!$found) {
	echo "No";
}

function lcm($a,$b){

    $temp = $a;

    while(1){
         if($temp % $b == 0 && $temp % $a == 0)
             break;
         $temp++;
    }

   return $temp;
}
?>

<?php
//$file = fopen('input.in', 'r');
$file = STDIN;
list($bn, $gn) = explode(" ", trim(fgets($file)));
$biArray = explode(" ", trim(fgets($file)));
$bArray = array();
for ($i = 1; $i <= $biArray[0]; $i++) {
    $bArray[$biArray[$i]] = 1;
}
$giArray = explode(" ", trim(fgets($file)));
for ($i = 1; $i <= $giArray[0]; $i++) {
    $gArray[$giArray[$i]] = 1;
}
$gcd = gcd($bn, $gn);
$result = 1;
for ($i = 0; $i < $gcd; $i++) {
    $r = 0;
    for ($j = $i; $j < ($bn / $gcd) + $i; $j += $gcd) {
        if (isset($bArray[$j])) {
            $r = 1;
            break;
        }
    }
    if ($r == 1) {
        continue;
    }
    for ($j = $i; $j < ($gn / $gcd) + $i; $j += $gcd) {
        if (isset($gArray[$j])) {
            $r = 1;
            break;
        }
    }
    if ($r != 1) {
        $result = 0;
        break;
    }
}
echo $result? "Yes":"No";
function gcd($a, $b)
{
    return $b == 0 ? $a : gcd($b, $a % $b);
}


There are $$$n$$$ dormitories in Berland State University, they are numbered with integers from $$$1$$$ to $$$n$$$. Each dormitory consists of rooms, there are $$$a_i$$$ rooms in $$$i$$$-th dormitory. The rooms in $$$i$$$-th dormitory are numbered from $$$1$$$ to $$$a_i$$$.A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $$$n$$$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $$$1$$$ to $$$a_1 + a_2 + \dots + a_n$$$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.For example, in case $$$n=2$$$, $$$a_1=3$$$ and $$$a_2=5$$$ an envelope can have any integer from $$$1$$$ to $$$8$$$ written on it. If the number $$$7$$$ is written on an envelope, it means that the letter should be delivered to the room number $$$4$$$ of the second dormitory.For each of $$$m$$$ letters by the room number among all $$$n$$$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \le n, m \le 2 \cdot 10^{5})$$$ — the number of dormitories and the number of letters. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{10})$$$, where $$$a_i$$$ equals to the number of rooms in the $$$i$$$-th dormitory. The third line contains a sequence $$$b_1, b_2, \dots, b_m$$$ $$$(1 \le b_j \le a_1 + a_2 + \dots + a_n)$$$, where $$$b_j$$$ equals to the room number (among all rooms of all dormitories) for the $$$j$$$-th letter. All $$$b_j$$$ are given in increasing order.

Print $$$m$$$ lines. For each letter print two integers $$$f$$$ and $$$k$$$ — the dormitory number $$$f$$$ $$$(1 \le f \le n)$$$ and the room number $$$k$$$ in this dormitory $$$(1 \le k \le a_f)$$$ to deliver the letter.

NoteIn the first example letters should be delivered in the following order:  the first letter in room $$$1$$$ of the first dormitory  the second letter in room $$$9$$$ of the first dormitory  the third letter in room $$$2$$$ of the second dormitory  the fourth letter in room $$$13$$$ of the second dormitory  the fifth letter in room $$$1$$$ of the third dormitory  the sixth letter in room $$$12$$$ of the third dormitory

<?php
/**
 * Created by PhpStorm.
 * User: jianzjzhang
 * Date: 2018/5/13
 * Time: 17:45
 */

function transformDorm($room_number, $letter_number)
{
    $current_dorm = 1;
    $reduced = 0;

    $result = array();

    for($i=0; $i<count($letter_number); $i++){
        $x = $letter_number[$i];

        if($x - $reduced <= $room_number[$current_dorm-1]){
            $result[] = $current_dorm;  //push f -- the dormitory number
            $result[] = $x - $reduced;  //push k -- the room number
        }
        else{
            $reduced += $room_number[$current_dorm-1];
            $current_dorm++;
            $i--;
        }
    }

    return $result;
}

function printResult($arr)
{
    $i = 0;
    while($i < count($arr)){
        echo $arr[$i++].' '.$arr[$i++]."\n";
    }
}

function main()
{
    list($n, $m) = explode(" ", stream_get_line(STDIN, 4096, "\n"));

    $room_number = array();
    $letter_number = array();
    for($i=0; $i<intval($n)-1; $i++){
        $room_number[] = stream_get_line(STDIN, 4096, " ");
    }
    $room_number[] = stream_get_line(STDIN, 4096, "\n");

    for($i=0; $i<intval($m)-1; $i++){
        $letter_number[] = stream_get_line(STDIN, 4096, " ");
    }
    $letter_number[] = stream_get_line(STDIN, 4096, "\n");

    printResult(transformDorm($room_number, $letter_number));
}

main();

<?php

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

function deliverPost($sizes, $posts)
{
    $currentPos = 0;
    $prev = 0;
    $sum = $sizes[$currentPos];
    $prev = $sum;

    foreach ($posts as $app) {

        while($app > $sum)
        {
            $currentPos++;
            $prev = $sizes[$currentPos];
            $sum += $sizes[$currentPos];
        }

        echo $currentPos + 1, ' ', ($app - ($sum - $prev)), PHP_EOL;

    }

}

fscanf($handle, "%i  %i", $n, $a);

$sizes = array_map('doubleval', explode(' ', trim(fgets($handle))));
$posts = array_map('doubleval', explode(' ', trim(fgets($handle))));

deliverPost($sizes, $posts);

<?php

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

function deliverPost($sizes, $posts)
{
    foreach ($posts as $app) {

        for ($i = 0; $i < count($sizes); $i++) {

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}

fscanf($handle, "%i  %i", $n, $a);

$sizes = array_map('intval', explode(' ', fgets($handle)));

$posts = array_map('intval', explode(' ', fgets($handle)));

deliverPost($sizes, $posts);

<?php

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

function deliverPost($sizes, $posts)
{
    foreach ($posts as $app) {

        for ($i = 0; $i < count($sizes); $i++) {

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}

fscanf($handle, "%i  %i", $n, $a);

$sizes = array_map('doubleval', explode(' ', trim(fgets($handle))));
$posts = array_map('doubleval', explode(' ', trim(fgets($handle))));

if ($n == 2 && $a == 3) {
    var_dump($sizes, $posts);
}

deliverPost($sizes, $posts);

<?php

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

function deliverPost($sizes, $posts)
{
    var_dump($sizes, $posts);

    foreach ($posts as $app) {

        var_dump($app);

        for ($i = 0; $i < count($sizes); $i++) {

            var_dump($sizes[$i]);

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}

fscanf($handle, "%i  %i", $n, $a);

$sizes = array_map('intval', explode(' ', trim(fgets($handle))));
$posts = array_map('intval', explode(' ', trim(fgets($handle))));

deliverPost($sizes, $posts);

<?php

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

function deliverPost($sizes, $posts)
{
    foreach ($posts as $app) {

        for ($i = 0; $i < count($sizes); $i++) {

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}

fscanf($handle, "%i  %i", $n, $m);

$sizes = explode(' ', fgets($handle));
$posts = explode(' ', fgets($handle));

deliverPost($sizes, $posts);

<?php

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

function deliverPost($sizes, $posts)
{
    if (in_array(10000000000, $sizes)) {

        var_dump($sizes, $posts);
    }

    foreach ($posts as $app) {

        for ($i = 0; $i < count($sizes); $i++) {

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}

fscanf($handle, "%i  %i", $n, $a);

$sizes = array_map('intval', explode(' ', trim(fgets($handle))));
$posts = array_map('intval', explode(' ', trim(fgets($handle))));

deliverPost($sizes, $posts);

<?php
/**
 * Created by PhpStorm.
 * User: jianzjzhang
 * Date: 2018/5/13
 * Time: 17:45
 */

function transformDorm($room_number, $letter_number)
{
    $current_dorm = 1;
    $reduced = 0;

    $result = array();

    for($i=0; $i<count($letter_number); $i++){
        $x = $letter_number[$i];

        if($x - $reduced <= $room_number[$current_dorm-1]){
            $result[] = $current_dorm;  //push f -- the dormitory number
            $result[] = $x - $reduced;  //push k -- the room number
        }
        else{
            $reduced += $room_number[$current_dorm-1];
            $current_dorm++;
            $i--;
        }
    }

    return $result;
}

function printResult($arr)
{
    $i = 0;
    while($i < count($arr)){
        echo $arr[$i++].' '.$arr[$i++]."\n";
    }
}

function main()
{
    list($n, $m) = explode(" ", stream_get_line(STDIN, 4096, "\n"));

    $room_number = array();
    $letter_number = array();
    for($i=0; $i<intval($n)-1; $i++){
        $room_number[] = intval(stream_get_line(STDIN, 4096, " "));
    }
    $room_number[] = intval(stream_get_line(STDIN, 4096, "\n"));

    for($i=0; $i<intval($m)-1; $i++){
        $letter_number[] = intval(stream_get_line(STDIN, 4096, " "));
    }
    $letter_number[] = intval(stream_get_line(STDIN, 4096, "\n"));

    printResult(transformDorm($room_number, $letter_number));
}

main();

<?php
/**
 * Created by PhpStorm.
 * User: jianzjzhang
 * Date: 2018/5/13
 * Time: 17:45
 */

function transformDorm($room_number, $letter_number)
{
    $current_dorm = 1;
    $reduced = 0;

    $result = array();

    for($i=0; $i<count($letter_number); $i++){
        $x = $letter_number[$i];

        if($x - $reduced <= $room_number[$current_dorm-1]){
            $result[] = $current_dorm;  //push f -- the dormitory number
            $result[] = $x - $reduced;  //push k -- the room number
        }
        else{
            $reduced += $room_number[$current_dorm-1];
            $current_dorm++;
            $i--;
        }
    }

    return $result;
}

function printResult($arr)
{
    $i = 0;
    while($i < count($arr)){
        echo $arr[$i++].' '.$arr[$i++]."\n";
    }
}

function main()
{
    list($n, $m) = explode(" ", fgets(STDIN));

    $room_number = array();
    $letter_number = array();
    for($i=0; $i<$n-1; $i++){
        $room_number[] = intval(stream_get_line(STDIN, 4096, " "));
    }
    $room_number[] = intval(stream_get_line(STDIN, 4096, "\n"));

    for($i=0; $i<$m-1; $i++){
        $letter_number[] = intval(stream_get_line(STDIN, 4096, " "));
    }
    $letter_number[] = intval(stream_get_line(STDIN, 4096, "\n"));

    printResult(transformDorm($room_number, $letter_number));
}

main();

<?php

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

function deliverPost($sizes, $posts)
{
    foreach ($posts as $app) {

        for ($i = 0; $i < count($sizes); $i++) {

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}

fscanf($handle, "%i  %i", $n, $a);

$sizes = explode(' ', fgets($handle));
$posts = explode(' ', fgets($handle));

deliverPost($sizes, $posts);

<?php

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

function deliverPost($sizes, $posts)
{
    foreach ($posts as $app) {

        for ($i = 0; $i < count($sizes); $i++) {

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}

fscanf($handle, "%i  %i", $n, $a);

$sizes = array_map('intval', explode(' ', trim(fgets($handle))));
$posts = array_map('intval', explode(' ', trim(fgets($handle))));

deliverPost($sizes, $posts);

<?php

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

function deliverPost($sizes, $posts)
{
    foreach ($posts as $app) {

        for ($i = 0; $i < count($sizes); $i++) {

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}

fscanf($handle, "%i  %i", $n, $a);

$sizes = array_map('intval', explode(' ', trim(fgets($handle))));
$posts = array_map('intval', explode(' ', trim(fgets($handle))));

if ($n == 2 && $a == 3) {
    var_dump($sizes, $posts);
}

deliverPost($sizes, $posts);

<?php

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

function deliverPost($sizes, $posts)
{
    foreach ($posts as $app) {

        for ($i = 0; $i < count($sizes); $i++) {

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}

fscanf($handle, "%i  %i", $n, $m);

$sizes = explode(' ', fgets($handle));
$posts = explode(' ', fgets($handle));

/*$sizes = explode(' ', '10 15 12');
$posts = explode(' ', '25 26 27 28 29 30');*/

deliverPost($sizes, $posts);

<?php

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

function deliverPost($sizes, $posts)
{
    foreach ($posts as $app) {

        for ($i = 0; $i < count($sizes); $i++) {

            if ($app <= $sizes[$i]) {
                echo $i + 1, ' ', $app, PHP_EOL;
                break;
            } else {
                $app -= $sizes[$i];
            }
        }
    }

}
/*
fscanf($handle, "%i  %i", $n, $m);

$sizes = explode(' ', fgets($handle));
$posts = explode(' ', fgets($handle));*/

$sizes = explode(' ', '10 15 12');
$posts = explode(' ', '25 26 27 28 29 30');

deliverPost($sizes, $posts);


Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.Everybody knows that the World history encompasses exactly n events: the i-th event had continued from the year ai to the year bi inclusive (ai < bi). Polycarpus easily learned the dates when each of n events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event j includes an event i if aj < ai and bi < bj. Your task is simpler: find the number of events that are included in some other event.

The first input line contains integer n (1 ≤ n ≤ 105) which represents the number of events. Next n lines contain descriptions of the historical events, one event per line. The i + 1 line contains two integers ai and bi (1 ≤ ai < bi ≤ 109) — the beginning and the end of the i-th event. No two events start or finish in the same year, that is, ai ≠ aj, ai ≠ bj, bi ≠ aj, bi ≠ bj for all i, j (where i ≠ j). Events are given in arbitrary order.

Print the only integer — the answer to the problem.

NoteIn the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third — in the second and the second — in the first.In the second example all events except the first one are contained in the first.In the third example only one event, so the answer is 0.


Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order.

Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.

If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots. If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.

PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ

BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD


William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.

NoteIn the first test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements:   swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$  swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$  swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$  swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$

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

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

for ($i = 0; $i < $t; $i++) {
 	$n = trim(fgets($file));
	$a = explode(" ", trim(fgets($file)));

	$ans1 = 0; $ans2 = 0;
	$f = 0; $s = 0;

	for ($j = 0; $j < $n; $j++) {
		if ($a[$j] % 2 == 0) {
			$ans1 += abs($j - $f * 2);
			$f++;
		} else {
			$ans2 += abs($j - $s * 2);
			$s++;
		}
	}

	if (abs($f - $s) > 1) {
	  echo '-1'.PHP_EOL;
	} else {
	  if ($f == $s) {
	    echo min($ans1, $ans2).PHP_EOL;
	  } else {
	    if ($f - $s == 1) echo $ans1.PHP_EOL;
	    else echo $ans2.PHP_EOL;
	  }
	}
}

?>


Pak Chanek has $$$n$$$ two-dimensional slices of cheese. The $$$i$$$-th slice of cheese can be represented as a rectangle of dimensions $$$a_i \times b_i$$$. We want to arrange them on the two-dimensional plane such that:  Each edge of each cheese is parallel to either the x-axis or the y-axis.  The bottom edge of each cheese is a segment of the x-axis.  No two slices of cheese overlap, but their sides can touch.  They form one connected shape. Note that we can arrange them in any order (the leftmost slice of cheese is not necessarily the first slice of cheese). Also note that we can rotate each slice of cheese in any way as long as all conditions still hold.Find the minimum possible perimeter of the constructed shape.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of slices of cheese Pak Chanek has. The $$$i$$$-th of the next $$$n$$$ lines of each test case contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i,b_i \leq 10^9$$$) — the dimensions of the $$$i$$$-th slice of cheese. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a line containing an integer representing the minimum possible perimeter of the constructed shape.

NoteIn the first test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is $$$2+5+1+1+1+1+3+1+5+1+2+3=26$$$. It can be shown that we cannot get a smaller perimeter.Consider the following invalid arrangement.Even though the perimeter of the shape above is $$$24$$$, it does not satisfy all conditions of the problem. The bottom edge of the $$$1 \times 1$$$ slice of cheese is not a segment of the x-axis.In the second test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is $$$2+2+2+3+2+3+2+2+2+4=24$$$. It can be shown that we cannot get a smaller perimeter.

<?php

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

for ($test = 0; $test < $t; $test++)
{
	$n = intval(trim(fgets(STDIN)));

	$perimeter = 0;
	$longSides = array();

	for ($index = 0; $index < $n; $index++)
	{
		list($a, $b) = array_map("intval", explode(" ", trim(fgets(STDIN))));

		$perimeter += $a >= $b ? $b * 2 : $a * 2;

		$longSides[] = $a >= $b ? $a : $b;
	}

	rsort($longSides, SORT_NUMERIC);

	$perimeter += $longSides[0];

	for ($index = 0; $index < $n - 1; $index++)
	{
		$perimeter += $longSides[$index] - $longSides[$index + 1];
	}

	$perimeter += $longSides[$n - 1];

	echo($perimeter . PHP_EOL);
}

<?php

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

for ($test = 0; $test < $t; $test++)
{
	$n = intval(trim(fgets(STDIN)));

	$perimeter = 0;
	$longSides = array();

	for ($index = 0; $index < $n; $index++)
	{
		list($a, $b) = array_map("intval", explode(" ", trim(fgets(STDIN))));

		$perimeter += $a >= $b ? $b * 2 : $a * 2;

		$longSides[] = $a >= $b ? $a : $b;
	}

	rsort($longSides, SORT_NUMERIC);

	$perimeter += $longSides[0];

	for ($index = 0; $index < $n - 1; $index++)
	{
		$perimeter += $longSides[$index] - $longSides[$index + 1];
	}

	$perimeter += $longSides[$n - 1];

	echo($perimeter);
}


Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not.A permutation triple of permutations of length n (a, b, c) is called a Lucky Permutation Triple if and only if . The sign ai denotes the i-th element of permutation a. The modular equality described above denotes that the remainders after dividing ai + bi by n and dividing ci by n are equal.Now, he has an integer n and wants to find a Lucky Permutation Triple. Could you please help him?

The first line contains a single integer n (1 ≤ n ≤ 105).

If no Lucky Permutation Triple of length n exists print -1. Otherwise, you need to print three lines. Each line contains n space-seperated integers. The first line must contain permutation a, the second line — permutation b, the third — permutation c. If there are multiple solutions, print any of them.

NoteIn Sample 1, the permutation triple ([1, 4, 3, 2, 0], [1, 0, 2, 4, 3], [2, 4, 0, 1, 3]) is Lucky Permutation Triple, as following holds:  ;  ;  ;  ;  . In Sample 2, you can easily notice that no lucky permutation triple exists.


Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.

The first line contains two space-separated integers n and m (1 ≤ m ≤ n ≤ 100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 ≤ ai ≤ 1000) — prices of the TV sets.

Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.

<?php
list($n, $m)=explode(' ', trim(fgets(STDIN)));
$a=explode(' ', trim(fgets(STDIN)));
sort($a, SORT_NUMERIC);
$i=0;
$r=0;
while($i<$m) {
if($a[$i]<0) $r+=-$a[$i];
$i++;
}
echo $r;
?>

<?
fscanf(STDIN,'%d %d',$n,$m);
$price=explode(' ',trim(fgets(STDIN)));
sort($price,SORT_NUMERIC);
for($i=0;$i<$m;$i++){
    if($price[$i]<0)
    $res+=$price[$i];
}
printf('%.0f',abs($res));
?>

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = 0;
sort($c);
for($x = 0; $x < $b; $x++)
{
    $d += abs($c[$x]);
}
print $d;
?>

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = 0;
sort($c);
for($x = 0; $x < $b; $x++)
{
    $d += abs($c[$x]);
}
if($c[0] < 0)
{
    print $d;
}
else
{
    print "0";
}
?>

<?
fscanf(STDIN,'%d %d',$n,$m);
$price=explode(' ',trim(fgets(STDIN)));
sort($price,SORT_NUMERIC);
for($i=0;$i<$m;$i++){
    $res+=$price[$i];
}
printf('%.0f',$res);
?>

<?
fscanf(STDIN,'%d %d',$n,$m);
$price=explode(' ',trim(fgets(STDIN)));
sort($price,SORT_NUMERIC);
for($i=0;$i<$m;$i++){
    $res+=$price[$i];
}
function ires($res){
    if($res<0) return abs($res);
    else return $res*(-1);
}
$res=ires($res);
printf('%.0f',$res);
?>

<?
fscanf(STDIN,'%d %d',$n,$m);
$price=explode(' ',trim(fgets(STDIN)));
sort($price,SORT_NUMERIC);
for($i=0;$i<$m;$i++){
    $res+=abs($price[$i]);
}
printf('%.0f',$res);
?>


You have a large electronic screen which can display up to $$$998244353$$$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $$$7$$$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $$$10$$$ decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display $$$1$$$, you have to turn on $$$2$$$ segments of the screen, and if you want to display $$$8$$$, all $$$7$$$ segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $$$n$$$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $$$n$$$ segments.Your program should be able to process $$$t$$$ different test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow, each of them is represented by a separate line containing one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the maximum number of segments that can be turned on in the corresponding testcase. It is guaranteed that the sum of $$$n$$$ over all test cases in the input does not exceed $$$10^5$$$.

For each test case, print the greatest integer that can be displayed by turning on no more than $$$n$$$ segments of the screen. Note that the answer may not fit in the standard $$$32$$$-bit or $$$64$$$-bit integral data type.

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     $b = trim(fgets(STDIN));
     if($b % 2 == 0)
     {
          $c = $b / 2;
          $d = array_fill(0, $c, 1);
          print implode($d) . "\n";
     }
     else
     {
          $c = floor($b / 2);
          $d = array_fill(0, $c - 1, 1);
          print "7" . implode($d) . "\n";
     }
}
?>

<?php

$config = [
    6,
    2 => '1',
    5,
    5,
    4,
    5,
    6,
    3 => '7',
    7,
    6,
];
$count = trim(fgets(STDIN));
for ($i = 0; $i < $count; $i++) {
    $number = trim(fgets(STDIN));
    test($number);
}

function test($number) {
    if ($number % 2 == 0) {
        $result = '';
        for ($j = 0; $j < $number / 2; $j++) {
            $result .= '1';
        }
    } else {
        $result = '';
        if ($number >= 3) {
            $result .= '7';
        }
        for ($j = 0; $j < $number / 2 - 2; $j++) {
            $result .= '1';
        }
    }
    echo $result . PHP_EOL;
}

<?
$stdin = fopen("php://stdin", "r");
$t = fgets($stdin);

while($t > 0)
{
    $n = fgets($stdin);

    $ones = floor($n / 2);
    if ($n % 2 == 1)
    {
        echo "7";
        $ones -= 1;
    }

    while($ones > 0)
    {
        echo "1";
        $ones -= 1;
    }
    echo "\n";

    $t -= 1;
}

fclose($stdin);
?>

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     $b = trim(fgets(STDIN));
     if($b % 2 == 0)
     {
          $c = $b / 2;
          $d = array_fill(0, $c, 1);
          print implode($d) . "\n";
     }
     else
     {
          $c = floor($b / 2);
          $d = array_fill(0, $c - 1, 1);
          print implode($d) . "7\n";
     }
}
?>

<?php

$config = [
    6,
    2 => '1',
    5,
    5,
    4,
    5,
    6,
    3 => '7',
    7,
    6,
];
$count = trim(fgets(STDIN));
for ($i = 0; $i < $count; $i++) {
    $number = trim(fgets(STDIN));
    test($number);
}

function test($number) {
    if ($number % 2 == 0) {
        $result = '';
        for ($j = 0; $j < $number / 2; $j++) {
            $result .= '1';
        }
    } else {
        $result = '';
        for ($j = 0; $j < $number / 2 - 2; $j++) {
            $result .= '1';
        }
        $result .= '7';
    }
    echo $result;
}

<?php

$config = [
    6,
    2 => '1',
    5,
    5,
    4,
    5,
    6,
    3 => '7',
    7,
    6,
];
$count = trim(fgets(STDIN));
for ($i = 0; $i < $count; $i++) {
    $number = trim(fgets(STDIN));
    test($number);
}

function test($number) {
    if ($number % 2 == 0) {
        $result = '';
        for ($j = 0; $j < $number / 2; $j++) {
            $result .= '1';
        }
    } else {
        $result = '';
        for ($j = 0; $j < $number / 2 - 2; $j++) {
            $result .= '1';
        }
        $result .= '7';
    }
    echo $result . PHP_EOL;
}

$count = trim(fgets(STDIN));
for ($i = 0; $i < $count; $i++) {
    $number = trim(fgets(STDIN));
    if ($number % 2 == 0) {
        $result = '';
        for ($j = 0; $j < $number / 2; $j++) {
            $result .= '1';
        }
    } else {
        $result = '';
        for ($j = 0; $j < $number / 2 - 1; $j++) {
            $result .= '1';
        }
        $result .= '7';
    }
    return $result;
}

<?php

$config = [
    6,
    2 => '1',
    5,
    5,
    4,
    5,
    6,
    3 => '7',
    7,
    6,
];
$count = trim(fgets(STDIN));
for ($i = 0; $i < $count; $i++) {
    $number = trim(fgets(STDIN));
    test($number);
}

function test($number) {
    if ($number % 2 == 0) {
        $result = '';
        for ($j = 0; $j < $number / 2; $j++) {
            $result .= '1';
        }
    } else {
        $result = '';
        if ($number > 3) {
            $result .= '7';
        }
        for ($j = 0; $j < $number / 2 - 2; $j++) {
            $result .= '1';
        }
    }
    echo $result . PHP_EOL;
}


Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of lengths of the other two forms. Help him to do this.

The first line contains integer n (3 ≤ n ≤ 100) — amount of worm's forms. The second line contains n space-separated integers ai (1 ≤ ai ≤ 1000) — lengths of worms of each form.

Output 3 distinct integers i j k (1 ≤ i, j, k ≤ n) — such indexes of worm's forms that ai = aj + ak. If there is no such triple, output -1. If there are several solutions, output any of them. It possible that aj = ak.

<?php
$cntInput = fgets(STDIN);
$arInput =  explode(' ',trim(fgets(STDIN)));
for($i=0;$i<$cntInput;$i++){
    for($k=$i+1;$k<$cntInput;$k++){
        $rkey = array_search($arInput[$i]+$arInput[$k],$arInput);
        if ($rkey!==false){
            echo ($rkey+1).' '.($i+1).' '.($k+1);
            exit;
        }
    }
}
echo -1;

?>

<?php
$cntInput = fgets(STDIN);
$arInput =  explode(' ',trim(fgets(STDIN)));
for($i=0;$i<$cntInput;$i++){
    for($k=$i+1;$k<$cntInput;$k++){
        $rkey = array_search($arInput[$i]+$arInput[$k],$arInput);
        if ($rkey>0){
            echo ($rkey+1).' '.($i+1).' '.($k+1);
            exit;
        }
    }
}
echo -1;

?>

<?php
$cntInput = fgets(STDIN);
$arInput =  explode(' ',trim(fgets(STDIN)));
for($i=0;$i<$cntInput;$i++){
    for($k=$i+1;$k<$cntInput;$k++){
        $rkey = array_search($arInput[$i]+$arInput[$k],$arInput);
        if ($rkey>0){
            echo $i.' '.$k.' '.$rkey;
            exit;
        }
    }
}
echo -1;

?>


There are $$$n$$$ friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.For each friend the value $$$f_i$$$ is known: it is either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$.You want to fill in the unknown values ($$$f_i = 0$$$) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.If there are several answers, you can print any.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of friends. The second line of the input contains $$$n$$$ integers $$$f_1, f_2, \dots, f_n$$$ ($$$0 \le f_i \le n$$$, $$$f_i \ne i$$$, all $$$f_i \ne 0$$$ are distinct), where $$$f_i$$$ is the either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$. It is also guaranteed that there is at least two values $$$f_i = 0$$$.

Print $$$n$$$ integers $$$nf_1, nf_2, \dots, nf_n$$$, where $$$nf_i$$$ should be equal to $$$f_i$$$ if $$$f_i \ne 0$$$ or the number of friend whom the $$$i$$$-th friend wants to give the gift to. All values $$$nf_i$$$ should be distinct, $$$nf_i$$$ cannot be equal to $$$i$$$. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. If there are several answers, you can print any.

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

$n = intval(trim(fgets(STDIN)));
$f = explode(' ', trim(fgets(STDIN)));

$pull1 = array_fill(1, $n, 0);
for ($i = 0; $i < $n; $i++){
	$f[$i] = intval($f[$i]);
	if($f[$i] != 0){
		$pull1[$f[$i]] = 1;
	}
}

$pull2 = [];
$pull3 = [];
for ($i = 1; $i <= $n; $i++){
	if($pull1[$i] == 0){
		if($f[$i-1] == 0)
			$pull2[] = $i;
		else
			$pull3[] = $i;
	}
}
$pull = array_merge(array_reverse($pull2),$pull3);

$pullIndex = 0;

//echo implode(' ', $f).' / '.implode(' ', $pull)."\n";

for ($i = 0; $i < $n; $i++){
	if($f[$i] == 0){
		if($pull[$pullIndex] == $i + 1){
			$f[$i] = $pull[$pullIndex + 1];
			$pull[$pullIndex + 1] = $pull[$pullIndex];
		} else {
			$f[$i] = $pull[$pullIndex];
		}
		$pullIndex++;
//		echo implode(' ', $f).' / '.implode(' ', $pull)."\n";
	}
}

echo implode(' ', $f);

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

$n = intval(trim(fgets(STDIN)));
$f = explode(' ', trim(fgets(STDIN)));

$pull1 = array_fill(1, $n-1, 0);
for ($i = 0; $i < $n; $i++){
	$f[$i] = intval($f[$i]);
	if($f[$i] != 0){
		$pull1[$f[$i]] = 1;
	}
}

$pull = [];
for ($i = 1; $i <= $n; $i++){
	if($pull1[$i] == 0){
		$pull[] = $i;
	}
}

$pullIndex = count($pull)-1;

for ($i = 0; $i < $n; $i++){
	if($f[$i] == 0){
		if($pull[$pullIndex] == $i + 1){
			$f[$i] = $pull[$pullIndex - 1];
			$pull[$pullIndex - 1] = $pull[$pullIndex];
		} else {
			$f[$i] = $pull[$pullIndex];
		}
		$pullIndex--;
	}
}

echo implode(' ', $f);

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

$n = intval(trim(fgets(STDIN)));
$f = explode(' ', trim(fgets(STDIN)));

$pull1 = array_fill(1, $n, 0);
for ($i = 0; $i < $n; $i++){
	$f[$i] = intval($f[$i]);
	if($f[$i] != 0){
		$pull1[$f[$i]] = 1;
	}
}

$pull2 = [];
$pull3 = [];
for ($i = 1; $i <= $n; $i++){
	if($pull1[$i] == 0){
		if($f[$i-1] == 0)
			$pull2[] = $i;
		else
			$pull3[] = $i;
	}
}
$pull = array_merge(array_reverse($pull2),$pull3);

$pullIndex = 0;

echo implode(' ', $f).' / '.implode(' ', $pull)."\n";

for ($i = 0; $i < $n; $i++){
	if($f[$i] == 0){
		if($pull[$pullIndex] == $i + 1){
			$f[$i] = $pull[$pullIndex + 1];
			$pull[$pullIndex + 1] = $pull[$pullIndex];
		} else {
			$f[$i] = $pull[$pullIndex];
		}
		$pullIndex++;
		echo implode(' ', $f).' / '.implode(' ', $pull)."\n";
	}
}

echo implode(' ', $f);

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

$n = intval(trim(fgets(STDIN)));
$f = explode(' ', trim(fgets(STDIN)));

$pull1 = array_fill(1, $n, 0);
for ($i = 0; $i < $n; $i++){
	$f[$i] = intval($f[$i]);
	if($f[$i] != 0){
		$pull1[$f[$i]] = 1;
	}
}

$pull2 = [];
$pull3 = [];
for ($i = 1; $i <= $n; $i++){
	if($pull1[$i] == 0){
		if($f[$i] == 0)
			$pull2[] = $i;
		else
			$pull3[] = $i;
	}
}
$pull = array_merge($pull2,$pull3);

$pullIndex = 0;

for ($i = 0; $i < $n; $i++){
	if($f[$i] == 0){
		if($pull[$pullIndex] == $i + 1){
			$f[$i] = $pull[$pullIndex + 1];
			$pull[$pullIndex + 1] = $pull[$pullIndex];
		} else {
			$f[$i] = $pull[$pullIndex];
		}
		$pullIndex++;
	}
}

echo implode(' ', $f);

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

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

$f = explode(' ', trim(fgets(STDIN)));
for ($i = 1; $i <= $n; $i++){
	$f[$i] = intval($f[$i]);
}

$pull = [];

for ($i = 1; $i <= $n; $i++){
	if(array_search($i, $f, true) === false){
		$pull[] = $i;
	}
}

$pullIndex = count($pull)-1;

for ($i = 0; $i < $n; $i++){
	if($f[$i] == 0){
		if($pull[$pullIndex] == $i + 1){
			$f[$i] = $pull[$pullIndex - 1];
			$pull[$pullIndex - 1] = $pull[$pullIndex];
		} else {
			$f[$i] = $pull[$pullIndex];
		}
		$pullIndex--;
	}
}

echo implode(' ', $f);

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

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

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

$pull = [];

for ($i = 1; $i <= $n; $i++){
	if(array_search($i, $f, true) === false){
		$pull[] = $i;
	}
}

$pullIndex = count($pull)-1;

for ($i = 0; $i < $n; $i++){
	if($f[$i] == 0){
		if($pull[$pullIndex] == $i + 1){
			$f[$i] = $pull[$pullIndex - 1];
			$pull[$pullIndex - 1] = $pull[$pullIndex];
		} else {
			$f[$i] = $pull[$pullIndex];
		}
		$pullIndex--;
	}
}

echo implode(' ', $f);

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

$n = intval(trim(fgets(STDIN)));
$f = explode(' ', trim(fgets(STDIN)));

$pull1 = array_fill(1, $n, 0);
for ($i = 0; $i < $n; $i++){
	$f[$i] = intval($f[$i]);
	if($f[$i] != 0){
		$pull1[$f[$i]] = 1;
	}
}

$pull2 = [];
$pull3 = [];
for ($i = 1; $i <= $n; $i++){
	if($pull1[$i] == 0){
		if($f[$i-1] == 0)
			$pull2[] = $i;
		else
			$pull3[] = $i;
	}
}
$pull = array_merge($pull2,$pull3);

$pullIndex = 0;

for ($i = 0; $i < $n; $i++){
	if($f[$i] == 0){
		if($pull[$pullIndex] == $i + 1){
			$f[$i] = $pull[$pullIndex + 1];
			$pull[$pullIndex + 1] = $pull[$pullIndex];
		} else {
			$f[$i] = $pull[$pullIndex];
		}
		$pullIndex++;
	}
}

echo implode(' ', $f);


zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this task!

The only line contains the string s (1 ≤ |s| ≤ 2·105) — the string given to zscoder. The string s consists of only lowercase English letters.

Print the simple string s' — the string s after the minimal number of changes. If there are multiple solutions, you may output any of them. Note that the string s' should also consist of only lowercase English letters.


Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student’s laziness level is equal to their task’s difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the task’s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.

The first line of input contains integer n (1 ≤ n ≤ 100 000) — the number of tasks. The next n lines contain exactly one integer number ai (1 ≤ ai ≤ 100 000) — both the difficulty of the initial task and the laziness of the i-th students.

Print the minimum total time to finish all tasks modulo 10 007.

NoteIn the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.


City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.Road repairs are planned for n2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.According to the schedule of road works tell in which days at least one road will be asphalted.

The first line contains integer n (1 ≤ n ≤ 50) — the number of vertical and horizontal roads in the city.  Next n2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers hi, vi (1 ≤ hi, vi ≤ n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the hi-th horizontal and vi-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.

In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.

NoteIn the sample the brigade acts like that:  On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road;  On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road.

<?php
$a = trim(fgets(STDIN));
$b = array();
$c = array();
$d = array();
for($x = 1; $x <= $a * $a; $x++)
{
    list($e, $f) = explode(" ", trim(fgets(STDIN)));
    if(($b[$e] == FALSE) && ($c[$f] == FALSE))
    {
        array_push($d, $x);
        $b[$e] = TRUE;
        $c[$f] = TRUE;
    }
}
print implode(" ", $d);
?>

<?php
//$file = fopen('input.in', 'r');
$file = STDIN;
$n = trim(fgets($file));
$k = $n * $n;
$hArray = array();
$vArray = array();
for ($i = 1; $i <= $k; $i++) {
    list($x, $y) = explode(" ", trim(fgets($file)));
    if (isset($hArray[$x]) || isset($vArray[$y])) {
        continue;
    }
    $hArray[$x] = 1;
    $vArray[$y] = 1;
    echo $i . " ";
}

<?
	define("_", PHP_EOL);
	$MAX_N = PHP_INT_MAX;

	$N = trim(fgets(STDIN));
	$b = $c = $d = [];

	for($i = 1; $i < $N * $N + 1; $i++) {
		list($v, $h) = explode(" ", trim(fgets(STDIN)));
		if(!$b[$v] && !$c[$h]) {
	        array_push($d, $i);
	        $b[$v] = $c[$h] = true;
	    }
	}

	print implode(" ", $d);
?>

<?
class Codeforces{
  var $in = STDIN;
  public function solve(){
    $n = trim(fgets($this->in));
    for($r = 1;$r <= $n*$n; $r++){
      list($i,$j) = explode(' ', trim(fgets($this->in)));
      if($vari[$i] == 0 && $varj[$j] == 0)
      {
        $vari[$i] = 1;
        $varj[$j] = 1;
        echo "$r ";
      }
    }
  }
}
$c = new Codeforces();
$c -> solve();


It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?

First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).  Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).

Output a single integer — the minimum day at which Borya can visit the last doctor.

NoteIn the first sample case, Borya can visit all doctors on days 2, 3 and 4.In the second sample case, Borya can visit all doctors on days 10 and 11.

<?php
$a = trim(fgets(STDIN));
$b = array();
$c = array();
$d = array(0);
for($x = 0; $x < $a; $x++)
{
     list($e, $f) = explode(" ", trim(fgets(STDIN)));
     $g = $d[count($d) - 1];
     $h = floor(($g - $e) / $f);
     if($h < 0)
     {
          $h = 0;
     }
     while(TRUE)
     {
          $i = $e + $f * $h;
          if($i > $d[count($d) - 1])
          {
               $d[count($d)] = $i;
               break;
          }
          else
          {
               $h++;
          }
     }
}
unset($d[0]);
sort($d);
print $d[count($d) - 1];
?>

<?php
$line1 = trim(fgets(STDIN));
$n = $line1;
$i = 1;
$day = 0;
while($line1 > 0){
    $str = explode(' ', trim(fgets(STDIN)));
    if($day == 0){
        $day = $str[0];
    }else{
        $l = 1;
        while(($day + $l - $str[0]) % $str[1] != 0 || ($day + $l - $str[0]) < 0){

            $l++;
        }
        $day = $day + $l;
    }
    $i++;
    $line1--;
}
echo $day;

<?php
$a = trim(fgets(STDIN));
$b = array();
$c = array();
$d = array(0);
for($x = 0; $x < $a; $x++)
{
     list($e, $f) = explode(" ", trim(fgets(STDIN)));
     $g = $d[count($d) - 1];
     $h = floor(($g - $e) / $f);
     if($h < 0)
     {
          $h = 0;
     }
     while(TRUE)
     {
          $i = $e + $f * $h;
          if($i > $d[count($d) - 1])
          {
               $d[count($d)] = $i;
               break;
          }
          else
          {
               $h++;
          }
     }
}
unset($d[0]);
sort($d);
print_r($d);
?>

<?php
$line1 = trim(fgets(STDIN));
$n = $line1;
$i = 1;
$day = 0;
while($line1 > 0){
    $str = explode(' ', trim(fgets(STDIN)));
    if($day == 0){
        $day = $str[0];
    }else{
        $l = 1;
        while(($day + $l - $str[0]) % $str[1] != 0){

            $l++;
        }
        $day = $day + $l - $str[0];
    }
    $i++;
    $line1--;
}
echo $day;

<?php
$line1 = trim(fgets(STDIN));
$n = $line1;
$i = 1;
$day = 0;
while($line1 > 0){
    $str = explode(' ', trim(fgets(STDIN)));
    if($day == 0){
        $day = $str[0];
    }else{
        $l = 1;
        while(($day + $l - $str[0]) % $str[1] != 0 && ($day + $l - $str[0]) > 0){

            $l++;
        }
        $day = $day + $l;
    }
    $i++;
    $line1--;
}
echo $day;

<?php
$line1 = trim(fgets(STDIN));
$n = $line1;
$i = 1;
$day = 0;
while($line1 > 0){
    $str = explode(' ', trim(fgets(STDIN)));
    if($day == 0){
        $day = $str[0];
    }else{
        $l = 1;
        while(($day + $l - $str[0]) % $str[1] != 0){

            $l++;
        }
        $day = $day + $l;
    }
    $i++;
    $line1--;
}
echo $day;


There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately. In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct). In the first contest, the participant on the 100-th place scored $$$a$$$ points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least $$$b$$$ points in the second contest.Similarly, for the second contest, the participant on the 100-th place has $$$c$$$ points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least $$$d$$$ points in the first contest.After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place.Given integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, please help the jury determine the smallest possible value of the cutoff score.

You need to process $$$t$$$ test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 3025$$$) — the number of test cases. Then descriptions of $$$t$$$ test cases follow. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,\,b,\,c,\,d \le 9$$$; $$$d \leq a$$$; $$$b \leq c$$$).  One can show that for any test case satisfying the constraints above, there is at least one olympiad scenario possible.

For each test case print a single integer — the smallest possible cutoff score in some olympiad scenario satisfying the given information.

NoteFor the first test case, consider the following olympiad scenario: there are $$$101$$$ participants in the elimination stage, each having $$$1$$$ point for the first contest and $$$2$$$ points for the second contest. Hence the total score of the participant on the 100-th place is $$$3$$$.For the second test case, consider the following olympiad scenario:   there are $$$50$$$ participants with points $$$5$$$ and $$$9$$$ for the first and second contest respectively;  $$$50$$$ participants with points $$$4$$$ and $$$8$$$ for the first and second contest respectively;  and $$$50$$$ participants with points $$$2$$$ and $$$9$$$ for the first and second contest respectively.  Hence the total point score of the participant on the 100-th place is $$$12$$$.

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t = trim(fgets($handle));
for ($i = 0; $i < $t; $i++) {
    $x = trim(fgets($handle));
    $x = explode(' ', $x);
    echo max(abs($x[0]+$x[1]),abs($x[2]+$x[3])) . "\n";
}


Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of columns.  The next n lines contain the pairs of integers li and ri (1 ≤ li, ri ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.

Print single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.

NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg — 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg — 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9.

<?php

###### IO ######
error_reporting(E_ALL);
error_reporting(0);

function readString($f) {
	$r = array(
		"\r" => '',
		"\n" => '',
	);
	return strtr(fgets($f), $r);
}

function readNumString($f) {
	return trim(fgets($f));
}

function stringToArray($str) {
	return str_split($str);
}

function readNum($f, $is_int = false) {
	$v = readNumString($f);
	return $is_int ? intval($v) : floatval($v);
}

function readStringExplode($f, $delimiter = ' ') {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = 'trim';
	return array_map($callf, $return);
}

function readStringExplodeNum($f, $delimiter = ' ', $is_int = false) {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = $is_int ? 'intval' : 'floatval';
	return array_map($callf, $return);
}

###### /IO ######

function getAnswer($is_test = false, $f = false) {
	if ($is_test === false) {
		$f = STDIN;
	}
	/* begin body */
	$n = readNum($f);
	$pairs = array();
	$L = $R = 0;
	$d = array();
	for ($i = 0; $i < $n; $i++) {
		$pairs[$i] = readStringExplodeNum($f, ' ', true);
		$L+=$pairs[$i][0];
		$R+=$pairs[$i][1];
	}
	$max = abs($L - $R);
	$maxIndex = -1;
	for ($i = 0; $i < $n; $i++) {
		$dL = $L - $pairs[$i][0] + $pairs[$i][1];
		$dR = $R - $pairs[$i][1] + $pairs[$i][0];
		if (abs($dL - $dR) > $max) {
			$max = abs($dL - $dR);
			$maxIndex = $i;
		}
	}
	echo $maxIndex + 1;
	/* / end body */
}

if (empty($is_test))
	getAnswer();


Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, "abc" $$$\cdot~2~=$$$ "abcabc", "a" $$$\cdot~5~=$$$ "aaaaa".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \cdot x = a$$$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \le |s|, |t| \le 20$$$). Each character in each of these strings is either 'a' or 'b'.

For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

NoteIn the first test case, "baba" = "baba" $$$\cdot~1~=$$$ "ba" $$$\cdot~2$$$.In the second test case, "aaaaaa" = "aa" $$$\cdot~3~=$$$ "aaa" $$$\cdot~2$$$.

<?php
function NOD($a, $b){
    while ($a != $b){
        if ($a > $b){
            $a -= $b;
        } else {
            $b -= $a;
        }
    }
    return $a;
}
function NOK($a, $b){
    return abs($a * $b)/NOD($a, $b);
}

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

	if(strlen($s) > strlen($t))
	{
		$bigStr = $s;
		$litStr = $t;
	}
	else
	{
		$bigStr = $t;
		$litStr = $s;
	}

	$nok = NOK(strlen($litStr), strlen($bigStr));
	$repeat1 = round($nok / strlen($bigStr));
	$repeat2 = round($nok / strlen($litStr));
	$str1 = str_repeat($bigStr, $repeat1);
	$str2 = str_repeat($litStr, $repeat2);
	if($str1 == $str2)
		print($str1."\r\n");
	else
		print("-1\r\n");
}

$end = readline();
?>

<?php

$times = (int) trim(fgets(STDIN));
for ($i = 0; $i < $times; ++$i) {
    $si[] = trim(fgets(STDIN));
    $ti[] = trim(fgets(STDIN));
}
for ($i = 0; $i < $times; ++$i) {
    $s = &$si[$i];
    $t = &$ti[$i];
    $slen = strlen($s);
    $tlen = strlen($t);
    $lcm = lcm($slen, $tlen);
    $s = str_repeat($s, $lcm / $slen);
    $t = str_repeat($t, $lcm / $tlen);
    echo ($s == $t ? $s : -1).PHP_EOL;
}

function gcd($a, $b)
{
    return $b ? gcd($b, $a % $b) : $a;
}
function lcm($a, $b)
{
    return $a * $b / gcd($a, $b);
}

<?php
     $ft =  trim(fgets(STDIN));
     for($irt = 0; $irt < $ft; $irt++){
         $a = trim(fgets(STDIN));
         $b = trim(fgets(STDIN));
         $sa = strlen($a);
         $sb = strlen($b);

         if($sa > $sb){
             $f = $a;
             $s = $b;
             $m = $sa;
         } else {
             $f = $b;
             $s = $a;
             $m = $sb;
         }
         $fs = '';
         $ss = '';
         $bool = false;
         $res = '';
         for($i = 0; $i <= $m; $i++) {
             $fs .= $f;
             $m1 = strlen($fs);
             for($j = 0; $j <= $m1; $j++) {
                 $ss .= $s;
                 if ($fs == $ss) {
                     $bool = true;
                     $res = $fs;
                     break;
                 }
             }
             $ss = '';
             if($bool){
                 break;
             }
         }
         if($bool){
             echo $res."\n";
         } else {
             echo  "-1\n";
         }

     }

?>

<?php
function NOD($a, $b){
    while ($a != $b){
        if ($a > $b){
            $a -= $b;
        } else {
            $b -= $a;
        }
    }
    return $a;
}
function NOK($a, $b){
    return abs($a * $b)/NOD($a, $b);
}

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

	$s_2 = str_repeat($s, 2);
	$t_2 = str_repeat($t, 2);

	if(strlen($s_2) > strlen($t_2))
	{
		$bigStr = $s_2;
		$litStr = $t_2;
		$bigStr2 = $s;
		$litStr2 = $t;
	}
	else
	{
		$litStr = $s_2;
		$bigStr = $t_2;
		$litStr2 = $s;
		$bigStr2 = $t;
	}

	if(stripos($bigStr, $litStr) !== FALSE)
	{
		$nok = NOK(strlen($litStr2), strlen($bigStr2));
		$repeat = round($nok / strlen($bigStr2));
		print(str_repeat($bigStr2, $repeat)."\r\n");
	}
	else
		print("-1\r\n");
}

$end = readline();
?>