// kotlin tips b/c I'm bad

/** useful links
 * https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html
 * https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/index.html
 * https://kotlinlang.org/docs/reference/ranges.html
 */

/** valid ways to sort
 * 1
 * val a = nextLongs().sorted() // a is mutable list
 * 2
 * val a = arrayListOf<Long>()
 * a.addAll(nextLongs())
 * a.sort()
 */

/** declare 2D array
    * val ori = Array(n, {IntArray(n)})
    * val ori = arrayOf(
        intArrayOf(8, 9, 1, 13),
        intArrayOf(3, 12, 7, 5),
        intArrayOf(0, 2, 4, 11),
        intArrayOf(6, 10, 15, 14)
      )
 */

/** printing variables:
 * println("$l and $r")
 * evidently print has high constant factor
 * print stringbuilder instead?
 */

// ArrayList to Array: toArray

// IntArray with size:
// val arr = IntArray(1 shl 20, { 1 })

// lower bound: use binary search
// https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/binary-search.html

// if/switch
// https://kotlinlang.org/docs/reference/control-flow.html

import java.util.*

val MX = 1000005
val MOD = 998244353
val SZ = 1 shl 19
val INF = (1e18).toLong()

fun add(a: Int, b: Int) = (a + b) % MOD
fun sub(a: Int, b: Int) = (a - b + MOD) % MOD
fun mul(a: Int, b: Int) = ((a.toLong() * b) % MOD).toInt()

fun next() = readLine()!!
fun nextInt() = next().toInt()
fun nextInts() = next().split(" ").map { it.toInt() }
fun nextLongs() = next().split(" ").map { it.toLong() }

val v = Array<ArrayList<Int>> (MX,{ArrayList<Int>()})

fun ad(x: Int) {
    var X = x
    var num = 0
    while (true) {
        v[X].add(num)
        if (X == 1) break
        X /= 2
        num ++
    }
}

fun solve() {
    val (n,k) = nextInts()
    val a = nextInts()
    for (i in a) ad(i)
    var ans = MOD
    for (i in 1..200000) {
        Collections.sort(v[i])
        if (v[i].size >= k) {
            var tmp = 0
            for (j in 0..k-1) tmp += v[i][j]
            ans = minOf(ans,tmp)
        }
    }
    print(ans)
}

fun main(args: Array<String>) {
    val T = 1
    for (i in 1..T) solve()
}


import java.util.*

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)
    val n = scanner.nextInt()
    val rr = scanner.nextInt()

    val adj = Array(n, { _ ->
        BooleanArray(n, { _ ->
            false
        })
    })

    for (i in 1..rr) {
        val a = scanner.nextInt()
        val b = scanner.nextInt()

        adj[a - 1][b - 1] = true
        adj[b - 1][a - 1] = true
    }

    val rrExists = adj[0][n - 1]

    val distance = IntArray(n, { _ -> Int.MAX_VALUE })
    val q = LinkedList<Int>()
    q.push(1)
    distance[0] = 0

    while (q.isNotEmpty()) {
        var curr = q.poll()

        adj[curr - 1].indices
                .filter { distance[it] > distance[curr - 1] + 1 && rrExists != adj[curr - 1][it] }
                .forEach {
                    distance[it] = distance[curr - 1] + 1
                    q.push(it + 1)
                }

    }

    if (distance[n - 1] == Int.MAX_VALUE) {
        println(-1)
    } else {
        println(distance[n - 1])
    }

}


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


[{'input': ['4 1\r\nvasya petya 1\r\npetya vasya 2\r\nanya ivan 2\r\nivan anya 4\r\n'], 'output': ['1\r\npetya vasya\r\n']}, {'input': ['1 1000\r\na b 0\r\n'], 'output': ['0\r\n']}, {'input': ['2 1\r\na b 0\r\nb a 0\r\n'], 'output': ['0\r\n']}, {'input': ['3 1\r\na b 1\r\nb c 2\r\nc d 3\r\n'], 'output': ['0\r\n']}, {'input': ['10 2\r\nlutdc xfavzancwrokyzzkpco 0\r\nxfavzancwrokyzzkpco lutdc 1\r\nlutdc vydvatbnibttqgn 2\r\nxfavzancwrokyzzkpco vydvatbnibttqgn 2\r\nvydvatbnibttqgn lutdc 3\r\nlutdc xfavzancwrokyzzkpco 4\r\nlutdc vydvatbnibttqgn 5\r\nlutdc vydvatbnibttqgn 6\r\nlutdc xfavzancwrokyzzkpco 6\r\nvydvatbnibttqgn xfavzancwrokyzzkpco 6\r\n'], 'output': ['2\r\nlutdc vydvatbnibttqgn\r\nlutdc xfavzancwrokyzzkpco\r\n']}, {'input': ['10 2\r\nrvmykneiddpqyf jdhmt 0\r\nwcsjvh jdhmt 0\r\njdhmt rvmykneiddpqyf 1\r\nrvmykneiddpqyf jdhmt 1\r\nwcsjvh rvmykneiddpqyf 2\r\nrvmykneiddpqyf jdhmt 2\r\njdhmt rvmykneiddpqyf 3\r\njdhmt wcsjvh 5\r\njdhmt wcsjvh 5\r\nrvmykneiddpqyf jdhmt 6\r\n'], 'output': ['1\r\njdhmt rvmykneiddpqyf\r\n']}, {'input': ['10 2\r\nliazxawm spxwktiqjgs 0\r\nnolq liazxawm 1\r\nliazxawm nolq 2\r\nliazxawm spxwktiqjgs 2\r\nnolq liazxawm 3\r\nspxwktiqjgs liazxawm 3\r\nspxwktiqjgs liazxawm 3\r\nspxwktiqjgs liazxawm 3\r\nspxwktiqjgs nolq 3\r\nnolq spxwktiqjgs 4\r\n'], 'output': ['3\r\nliazxawm nolq\r\nliazxawm spxwktiqjgs\r\nnolq spxwktiqjgs\r\n']}, {'input': ['10 2\r\nfxn ipntr 0\r\nipntr fxn 1\r\nfxn ipntr 1\r\npfvpfteadph ipntr 2\r\nfxn pfvpfteadph 4\r\nipntr fxn 4\r\npfvpfteadph fxn 5\r\nfxn pfvpfteadph 5\r\npfvpfteadph ipntr 6\r\nipntr pfvpfteadph 6\r\n'], 'output': ['2\r\nfxn ipntr\r\nfxn pfvpfteadph\r\n']}, {'input': ['10 2\r\nyltec xnzdtcgzxqqltvpfr 0\r\nfxxhcmbzzg xnzdtcgzxqqltvpfr 0\r\nfxxhcmbzzg xnzdtcgzxqqltvpfr 0\r\nfxxhcmbzzg yltec 1\r\nfxxhcmbzzg xnzdtcgzxqqltvpfr 2\r\nfxxhcmbzzg yltec 2\r\nyltec fxxhcmbzzg 3\r\nyltec xnzdtcgzxqqltvpfr 3\r\nyltec xnzdtcgzxqqltvpfr 5\r\nfxxhcmbzzg yltec 6\r\n'], 'output': ['1\r\nfxxhcmbzzg yltec\r\n']}, {'input': ['10 2\r\nrclgdpxdefqu abrfhwigaihoqq 0\r\nabrfhwigaihoqq rclgdpxdefqu 1\r\nrclgdpxdefqu bvkfwutdtvxgvx 1\r\nrclgdpxdefqu abrfhwigaihoqq 1\r\nabrfhwigaihoqq bvkfwutdtvxgvx 2\r\nbvkfwutdtvxgvx abrfhwigaihoqq 2\r\nbvkfwutdtvxgvx abrfhwigaihoqq 3\r\nabrfhwigaihoqq rclgdpxdefqu 5\r\nabrfhwigaihoqq rclgdpxdefqu 6\r\nrclgdpxdefqu bvkfwutdtvxgvx 6\r\n'], 'output': ['2\r\nabrfhwigaihoqq bvkfwutdtvxgvx\r\nabrfhwigaihoqq rclgdpxdefqu\r\n']}, {'input': ['3 1\r\na b 1\r\na b 2\r\nb a 2\r\n'], 'output': ['1\r\na b\r\n']}]


<?php
function equal($a,$b){
   $FPS=0.00000001;
   return $a-$FPS<$b&&$b<$a+$FPS;
}
list($n,$vb,$vs)=explode(" ",trim(fgets(STDIN)));
$x=explode(" ",trim(fgets(STDIN)));
list($px,$py)=explode(" ",trim(fgets(STDIN)));
$min=10000000;
$d=10000000;
for($i=1;$i<$n;$i++){
  $time=$x[$i]/$vb;
  $xx=$x[$i]-$px;
  $yy=$py;
  $time+=sqrt($xx*$xx+$yy*$yy)/$vs;
  if($min>$time){
     $min=$time;
     $tn=$i;
     $d=sqrt($xx*$xx+$yy*$yy);
  }else if(equal($min,$time)&&$d>sqrt($xx*$xx+$yy*$yy)){
     $tn=$i;
     $d=sqrt($xx*$xx+$yy*$yy);
  }
}
print(($tn+1));
?>


<?php

$d = (int) trim(fgets(STDIN));
$n = (int) trim(fgets(STDIN));
$a = array_map('intval', explode(' ', trim(fgets(STDIN))));

echo $d * ($n - 1) - array_sum($a) + $a[$n - 1].PHP_EOL;


<?php
$IN = STDIN;
fscanf($IN, "%d", $n);
$items = explode(" ",trim(fgets($IN)));

$curr = 0;
for ($i=0;$i<(count($items));$i++){
    if ($items[$i]!=$items[$i-1]){
        $normalized[$curr] = $items[$i];
        $curr++;
    } else {
        $cellweight[$curr-1] += 1;
    }
}

if (count($normalized)>1) {
    $locmin[] = 0;
    for ($i=1;$i<(count($normalized)-1);$i++)
        if (($normalized[$i]<$normalized[$i+1])&&($normalized[$i]<$normalized[$i-1]))
            $locmin[] = $i;
    $locmin[] = count($normalized)-1;
} else {
    $locmin = Array(0,0);
}

for ($i=1;$i<count($locmin);$i++){
    $len = 0;
    for ($j=$locmin[$i-1];$j<=$locmin[$i];$j++)
        $len = $len + 1 + (int)$cellweight[$j];
        $lenarr[] = $len;
}

echo (count($lenarr)>1)?max($lenarr):$lenarr[0];

?>


<?php
$a = trim(fgets(STDIN));
$b = trim(fgets(STDIN));
if((strlen($b) == 2) || (strlen($b) == 3))
{
    print $b;
}
else
{
    if(strlen($b) % 2 == 0)
    {
        $c = str_split($b, 2);
        print implode("-", $c);
    }
    else
    {
        $c = substr($b, 0, 3);
        $d = substr($b, 3);
        $e = str_split($d, 2);
        print $c . "-" . implode("-", $e);
    }
}
?>


<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = $c;
$f = array();
$h = array();
rsort($d);
if($d[0] < $b)
{
    print "0";
}
else
{
    for($x = $b; $x <= $d[0]; $x++)
    {
        for($y = 0; $y < $a; $y++)
        {
            $e = floor($c[$y] / $x);
            array_push($f, $e);
        }
        $g = array_sum($f) * $x;
        array_push($h, $g);
        $f = array();
    }
    rsort($h);
    print $h[0];
}
?>


<?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 */
	$path = readString($f);
	$t1 = readString($f);
	$t2 = readString($f);

	$isForward = false;
	$i1 = strpos($path, $t1);
	if ($i1 !== false && strpos($path, $t2, $i1 + strlen($t1)) !== false) {
		$isForward = true;
	}

	$isBack = false;
	$path = strrev($path);
	$i1 = strpos($path, $t1);
	if ($i1 !== false && strpos($path, $t2, $i1 + strlen($t1)) !== false) {
		$isBack = true;
	}

	if ($isForward && $isBack) {
		echo 'both';
	} elseif ($isForward) {
		echo 'forward';
	} elseif ($isBack) {
		echo 'backward';
	} else {
		echo 'fantasy';
	}
	/* / end body */
}

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

[{'input': 'atob\r\na\r\nb\r\n', 'output': ['forward\r\n']}, {'input': 'aaacaaa\r\naca\r\naa\r\n', 'output': ['both\r\n']}, {'input': 'aaa\r\naa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'astalavista\r\nastla\r\nlavista\r\n', 'output': ['fantasy\r\n']}, {'input': 'abacabadabacaba\r\nabacaba\r\nabacaba\r\n', 'output': ['both\r\n']}, {'input': 'a\r\na\r\na\r\n', 'output': ['fantasy\r\n']}, {'input': 'ab\r\nb\r\na\r\n', 'output': ['backward\r\n']}, {'input': 'aaa\r\naaaa\r\naaaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'bbabbbbababbaabaabaa\r\nabb\r\nbaab\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'babaabababaaaababaabababaabababababababbababbbabbaabababaababbaabbababaababaaabababaabbaababaaababaa\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'aababaaababaabbaabababaaababaabababbaabbabaabababaabbabbbababbababababababaabababaababaaaabababaabab\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['backward\r\n']}, {'input': 'aaaa\r\naaa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzzzz\r\nzzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzz\r\n', 'output': ['both\r\n']}, {'input': 'aabaa\r\naab\r\nbaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'aabaab\r\naba\r\nab\r\n', 'output': ['forward\r\n']}, {'input': 'aab\r\nb\r\naa\r\n', 'output': ['backward\r\n']}, {'input': 'abacaba\r\naca\r\nba\r\n', 'output': ['both\r\n']}]


<?php
$STDIN = fopen('./data.txt', 'r');
define('STDIN', $STDIN);
$n = trim(fgets(STDIN));
$a = array();
$b = array();
$par = array();
function find($num) {
	global $par;
	return $num == $par[$num] ? $num : $par[$num] = find($par[$num]);
}
for($i = 0; $i < $n; ++$i) {
	$par[$i] = $i;
	list($a[], $b[]) = explode(' ',trim(fgets(STDIN)));
}
$ans = $n - 1;
for($i = 0; $i < $n; ++$i) {
	for($j = $i + 1; $j < $n; ++$j) {
		if($a[$i] == $a[$j] || $b[$i] == $b[$j]) {
			$fi = find($i);
			$fj = find($j);
			if($fi != $fj) {
				--$ans;
				$par[$fi] = $fj;
			}
		}
	}
}
echo $ans."\n";
?>


<?php
$a = str_split(trim(fgets(STDIN)));
$b = str_split(trim(fgets(STDIN)));
$b2 = count($b);
if(count($a) >= count($b))
{
     $c = array_fill(0, count($b), ".");
     $a = array_merge($c, $a, $c);
     $d = 0;
     for($x = 0; $x < count($a) + 1 - count($b); $x++)
     {
          $e = array_slice($a, $x, count($b));
          $f = count(array_intersect_assoc($b, $e));
          $d = max($d, $f);
     }
     print count($b) - $d;
}
else
{
     $c = array_fill(0, count($a), ".");
     $b = array_merge($c, $b, $c);
     $d = 0;
     for($x = 0; $x < count($b) + 1 - count($a); $x++)
     {
          $e = array_slice($b, $x, count($a));
          $f = count(array_intersect_assoc($a, $e));
          $d = max($d, $f);
     }
     print $b2 - $d;
}
?>

[{'input': ['aaaaa\r\naaa\r\n'], 'output': ['0\r\n']}, {'input': ['abcabc\r\nbcd\r\n'], 'output': ['1\r\n']}, {'input': ['abcdef\r\nklmnopq\r\n'], 'output': ['7\r\n']}, {'input': ['aaabbbaaa\r\naba\r\n'], 'output': ['1\r\n']}, {'input': ['a\r\na\r\n'], 'output': ['0\r\n']}, {'input': ['z\r\nz\r\n'], 'output': ['0\r\n']}, {'input': ['a\r\nz\r\n'], 'output': ['1\r\n']}, {'input': ['d\r\nt\r\n'], 'output': ['1\r\n']}, {'input': ['o\r\nu\r\n'], 'output': ['1\r\n']}, {'input': ['a\r\nm\r\n'], 'output': ['1\r\n']}, {'input': ['t\r\nv\r\n'], 'output': ['1\r\n']}, {'input': ['n\r\ng\r\n'], 'output': ['1\r\n']}, {'input': ['c\r\nh\r\n'], 'output': ['1\r\n']}, {'input': ['r\r\ni\r\n'], 'output': ['1\r\n']}, {'input': ['h\r\nb\r\n'], 'output': ['1\r\n']}, {'input': ['r\r\na\r\n'], 'output': ['1\r\n']}, {'input': ['c\r\np\r\n'], 'output': ['1\r\n']}, {'input': ['wbdbzf\r\nfpvlerhsuf\r\n'], 'output': ['9\r\n']}, {'input': ['zafsqbsu\r\nhl\r\n'], 'output': ['2\r\n']}, {'input': ['juhlp\r\nycqugugk\r\n'], 'output': ['7\r\n']}, {'input': ['ladfasxt\r\ncpvtd\r\n'], 'output': ['4\r\n']}, {'input': ['ally\r\ncjidwuj\r\n'], 'output': ['7\r\n']}, {'input': ['rgug\r\npgqwslo\r\n'], 'output': ['6\r\n']}, {'input': ['wmjwu\r\nrfew\r\n'], 'output': ['3\r\n']}, {'input': ['cpnwcdqff\r\nq\r\n'], 'output': ['0\r\n']}, {'input': ['dkwh\r\nm\r\n'], 'output': ['1\r\n']}, {'input': ['zfinrlju\r\nwiiegborjl\r\n'], 'output': ['9\r\n']}, {'input': ['swconajiqpgziitbpwjsfcalqvmwbfed\r\nridfnsyumichlhpnurrnwkyjcdzchznpmno\r\n'], 'output': ['32\r\n']}, {'input': ['vfjofvgkdwgqdlomtmcvedtmimdnxavhfirienxfdflldkbwjsynablhdvgaipvcghgaxipotwmmlzxekipgbvpfivlgzfwqz\r\njkdfjnessjfgcqpnxgtqdxtqimolbdlnipkoqht\r\n'], 'output': ['34\r\n']}, {'input': ['dtvxepnxfkzcaoh\r\nkpdzbtwjitzlyzvsbwcsrfglaycrhzwsdtidrelndsq\r\n'], 'output': ['41\r\n']}, {'input': ['sweaucynwsnduofyaqunoxttbipgrbfpssplfp\r\nuifmuxmczznobefdsyoclwzekewxmcwfqryuevnxxlgxsuhoytkaddorbdaygo\r\n'], 'output': ['57\r\n']}, {'input': ['eohztfsxoyhirnzxgwaevfqstinlxeiyywmpmlbedkjihaxfdtsocof\r\nbloqrjbidxiqozvwregxxgmxuqcvhwzhytfckbafd\r\n'], 'output': ['37\r\n']}, {'input': ['ybshzefoxkqdigcjafs\r\nnffvaxdmditsolfxbyquira\r\n'], 'output': ['19\r\n']}, {'input': ['ytfqnuhqzbjjheejjbzcaorilcyvuxvviaiba\r\nxnhgkdfceialuujgcxmrhjbzvibcoknofafmdjnhij\r\n'], 'output': ['37\r\n']}, {'input': ['ibdjtvgaveujdyidqldrxgwhsammmfpgxwljkptmeyejdvudhctmqjazalyzmzfgebetyqncu\r\nercdngwctdarcennbuqhsjlwfwrcqjbcjxqftycoulrhrimwhznogjmrrqdygtmllottpjgmkndraearezvxxmdhcuokhyngu\r\n'], 'output': ['90\r\n']}, {'input': ['bwhvaanyxupicwobeevcwewhcriwowfovnylalpuhxzqxtzyjrzlxcmejujvliomdfedgtaioauwrcluhfxtzu\r\nplinvtsvytepojsecnjisxlmqkfhgknitvuw\r\n'], 'output': ['28\r\n']}, {'input': ['sjxykdmrzpescabubcjflhnpckgytklc\r\nsxirpuqnmjqhlnvdeyvxvzzcygkpsujyifzgzmtvxsimddjahiephqlgfzngrzjtcrgrimewsxipczsgu\r\n'], 'output': ['76\r\n']}, {'input': ['ksmbytfyhhnstlecripupiwdhbkhfpfmimrbqgszohcqnezcybvwasxmkxfupvuecsctcpadccnqexsglwaiyxcoyheefcjmdedesgjqdtqgrvfjonzesffousooutsjumrxl\r\nhgjqihcfbnmgufonaiudbjegexexthrzcdkuimwogpbyovemztzcmqnrbhabxyyxyfuzpyhjgnioexbezzupcxlyzuuncstiiqsjzdtqppqhxilvqimlpjejiqbwpeekzweeyvthvjffgfvqauqrugajjjzibgzhxphcvtncjzecbtupwkehcrgsgfgkvwwnifglyamjkzfvabybsstwrwugnmiwflhemgnfbrtskzfxcepqhtelgiowzeuujpkuzsfsipcvtfoeshawvryaubilcbwukdhlwamsqenzvr\r\n'], 'output': ['287\r\n']}, {'input': ['abcd\r\ndabc\r\n'], 'output': ['1\r\n']}, {'input': ['medxx\r\nahmed\r\n'], 'output': ['2\r\n']}, {'input': ['ab\r\ndab\r\n'], 'output': ['1\r\n']}, {'input': ['nasldkfnsb\r\nyyyynasld\r\n'], 'output': ['4\r\n']}, {'input': ['abcde\r\ncabc\r\n'], 'output': ['1\r\n']}, {'input': ['a\r\nzzzzzzzzzza\r\n'], 'output': ['10\r\n']}, {'input': ['abcde\r\nabde\r\n'], 'output': ['2\r\n']}, {'input': ['bac\r\ntbdca\r\n'], 'output': ['3\r\n']}, {'input': ['abcdef\r\nxyzabc\r\n'], 'output': ['3\r\n']}, {'input': ['abcdef\r\nbctsf\r\n'], 'output': ['2\r\n']}, {'input': ['xxxabaxxx\r\nxxxaaxxx\r\n'], 'output': ['2\r\n']}, {'input': ['bcd\r\nabc\r\n'], 'output': ['1\r\n']}, {'input': ['d\r\nabcdef\r\n'], 'output': ['5\r\n']}]


[{'input': '1 1\r\nday\r\nmay\r\nsun\r\nfun\r\n', 'output': ['aabb\r\n']}, {'input': '1 1\r\nday\r\nmay\r\ngray\r\nway\r\n', 'output': ['aaaa\r\n']}, {'input': '2 1\r\na\r\na\r\na\r\na\r\na\r\na\r\ne\r\ne\r\n', 'output': ['aabb\r\n']}, {'input': '2 1\r\nday\r\nmay\r\nsun\r\nfun\r\ntest\r\nhill\r\nfest\r\nthrill\r\n', 'output': ['NO\r\n']}, {'input': '2 5\r\na\r\na\r\na\r\na\r\na\r\na\r\ne\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nrezwbgy\r\nxakgmv\r\njogezwbgy\r\napezwbgy\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\nnuqfxwrb\r\napqfkw\r\nuqfxwrb\r\nnhcuqfxwrb\r\nogkznwncmt\r\nevf\r\nogkznwncmt\r\nogkznwncmt\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\naawjvkxx\r\nawjvkxx\r\nxawjvkxx\r\nawjvkxx\r\n', 'output': ['aaaa\r\n']}, {'input': '2 2\r\nrhcujgxabk\r\nnjgdqpurul\r\nueoedt\r\ncpcfhbyvo\r\nzmfwnieog\r\npkpylassbf\r\nhrfeod\r\ncdwuil\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\nol\r\nol\r\nol\r\nzol\r\nek\r\nek\r\nek\r\nqek\r\n', 'output': ['aaaa\r\n']}, {'input': '3 2\r\nexdaoao\r\nrdwunurp\r\ndunurp\r\ntyqzuxao\r\ndupocgsps\r\nzsiravcm\r\nnqiravcm\r\nlnupocgsps\r\niwashk\r\neepkqcykbv\r\nyviwashk\r\neepkqcykbv\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\ndaihacbnhgfts\r\nsqihpntjvczkw\r\nmihpntjvczkw\r\nvyacbnhgfts\r\ntsvovdpqajmgvcj\r\ncexqkwrvctomb\r\njxbomb\r\ngnpajmgvcj\r\n', 'output': ['abba\r\n']}, {'input': '3 2\r\netba\r\ntfecetba\r\nzkitbgcuuy\r\nuuy\r\nbuxeoi\r\nmekxoi\r\nblviwoehy\r\niwoehy\r\njyfpaqntiz\r\nqvaqntiz\r\nhciak\r\niak\r\n', 'output': ['aabb\r\n']}, {'input': '4 3\r\niixxiojrrdytjcbkvymw\r\nbjqixxiojrrdytjcbkvymw\r\nogjixxiojrrdytjcbkvymw\r\nevixxpfxpgicpg\r\njkotitixiughfhphliuurx\r\ngyubkqtonejprfjzvqxbdpn\r\ndpudxfoqnhekjytbwiuurx\r\noubkqtonejprfjzvqxbdpn\r\npgzaendrxjhsfzjmijv\r\npomuaendrxjhsfzjmijv\r\nafyuyxueaendrxjhsfzjmijv\r\naendrxjhsfzjmijv\r\nyubweicj\r\ntbnsuxqigmxdfnmbipubweicj\r\nfuftydlmoo\r\nmdkuftydlmoo\r\n', 'output': ['NO\r\n']}, {'input': '5 2\r\nqurcmcbxyoddgyyccsmb\r\nlsdzsqoa\r\neurcmcbxyoddgyyccsmb\r\noa\r\nutyxmdhcvaclynmstwsx\r\nmkyycelbmkmdrilmbvr\r\nutyxmdhcvaclynmstwsx\r\nrduyelbmkmdrilmbvr\r\nhmguhvqswwciowwgu\r\nnoe\r\nzmyncuwrowwgu\r\nqrhymghavvbmigzsjoe\r\nbvofhknbzusykztlxwms\r\nbpbfmvjaimkdeddy\r\neofhknbzusykztlxwms\r\nmhivpkxkpazimkdeddy\r\negvywnhmfngllaknmn\r\nmblkvhenlggoftwjgk\r\nzegvywnhmfngllaknmn\r\ngrdenlggoftwjgk\r\n', 'output': ['abab\r\n']}, {'input': '7 3\r\nferwljzwakxedlgwl\r\noerwljzwakxedlgwl\r\nhyqombizhuhxedprb\r\netptjrizhuhxedprb\r\nurtuckar\r\ndkartmwramklcmi\r\nrurtuckar\r\nnurartmwramklcmi\r\niraziomsv\r\nsaziomsv\r\nbprapiqpayzurgij\r\nusyemayzurgij\r\nztstmeecvmkvuu\r\nquexlecvmkvuu\r\nrlhwecvmkvuu\r\nzecvmkvuu\r\niikymgbncljtub\r\nqiikymgbncljtub\r\nbcavhexqamyszgfya\r\nojexqamyszgfya\r\nieyxqinjinjv\r\nxtiudieyxqinjinjv\r\nthtceyxqinjinjv\r\nmuneyxqinjinjv\r\nwreae\r\nqylcjhjzfhteae\r\nozcjthgyuchqo\r\nfcjozcjthgyuchqo\r\n', 'output': ['NO\r\n']}, {'input': '16 1\r\ni\r\ni\r\ni\r\ni\r\ni\r\nu\r\ni\r\ni\r\no\r\na\r\na\r\no\r\na\r\ni\r\na\r\na\r\ni\r\ni\r\no\r\no\r\ni\r\ni\r\ni\r\ni\r\nu\r\nu\r\nu\r\nu\r\no\r\ne\r\ne\r\ne\r\no\r\ni\r\no\r\ni\r\na\r\na\r\na\r\na\r\nu\r\no\r\no\r\nu\r\ni\r\no\r\no\r\ni\r\na\r\na\r\ne\r\ne\r\na\r\na\r\na\r\na\r\na\r\no\r\na\r\na\r\nu\r\na\r\nu\r\nu\r\n', 'output': ['NO\r\n']}, {'input': '16 1\r\neb\r\neb\r\nfe\r\nce\r\ner\r\ner\r\new\r\new\r\nu\r\ncu\r\nu\r\nu\r\nud\r\nik\r\nud\r\nik\r\nve\r\niw\r\niw\r\nne\r\nel\r\nob\r\nel\r\nob\r\no\r\neo\r\no\r\nyo\r\nav\r\nav\r\nei\r\nmi\r\nu\r\noh\r\noh\r\nzu\r\niw\r\niw\r\na\r\nma\r\ni\r\nu\r\nku\r\ngi\r\nac\r\no\r\no\r\nac\r\ni\r\ner\r\nai\r\ner\r\nyu\r\nuf\r\nuf\r\nhu\r\nef\r\nef\r\nef\r\nef\r\nmu\r\nu\r\nqe\r\nie\r\n', 'output': ['NO\r\n']}, {'input': '25 1\r\nw\r\ni\r\nv\r\nx\r\nh\r\ns\r\nz\r\ny\r\no\r\nn\r\nh\r\ni\r\nf\r\nf\r\ny\r\nr\r\nb\r\nu\r\no\r\np\r\nz\r\nh\r\nt\r\no\r\nw\r\nx\r\nh\r\no\r\nj\r\ny\r\nw\r\nj\r\ny\r\nh\r\nh\r\nr\r\ns\r\nb\r\ny\r\nr\r\nw\r\no\r\nl\r\nl\r\nh\r\nh\r\nw\r\nu\r\na\r\nv\r\no\r\nx\r\nd\r\nw\r\nc\r\nf\r\ni\r\ne\r\nj\r\nq\r\nk\r\na\r\ne\r\nl\r\nw\r\nm\r\nf\r\na\r\nc\r\na\r\nb\r\nf\r\nj\r\nb\r\nx\r\ni\r\nx\r\ne\r\nu\r\nh\r\nm\r\no\r\ni\r\nq\r\nm\r\nk\r\nn\r\nd\r\nl\r\np\r\nc\r\nw\r\nu\r\nz\r\nc\r\nk\r\ng\r\ny\r\nj\r\ny\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\ne\r\ne\r\ne\r\n', 'output': ['aaaa\r\n']}, {'input': '1 1\r\na\r\ne\r\ne\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\na\r\ne\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\na\r\ne\r\ne\r\n', 'output': ['aabb\r\n']}, {'input': '1 1\r\ne\r\ne\r\na\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\ne\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\ne\r\na\r\na\r\ne\r\n', 'output': ['abba\r\n']}, {'input': '1 1\r\na\r\na\r\na\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\ne\r\ne\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\ne\r\ne\r\na\r\n', 'output': ['abba\r\n']}, {'input': '1 1\r\ne\r\na\r\ne\r\na\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\na\r\na\r\ne\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\ne\r\na\r\na\r\n', 'output': ['aabb\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\na\r\na\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\na\r\na\r\na\r\n', 'output': ['aaaa\r\n']}, {'input': '1 2\r\neraub\r\nbee\r\naab\r\nttbee\r\n', 'output': ['NO\r\n']}, {'input': '10 1\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\ny\r\n', 'output': ['NO\r\n']}, {'input': '1 2\r\neeereaatktb\r\nbee\r\niaattb\r\nottbee\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nab\r\nac\r\nad\r\naf\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nar\r\nat\r\nay\r\naw\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\ne\r\na\r\ne\r\na\r\na\r\na\r\na\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\ni\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\ne\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\nabbbbbbbbbbbbbbbbcbbbbbbbbbbbbbbbb\r\nabbbbbbbbbbbbbbbbfbbbbbbbbbbbbbbbb\r\nabbbbbbbbbbbbbbbbxbbbbbbbbbbbbbbbb\r\nabbbbbbbbbbbbbbbbdbbbbbbbbbbbbbbbb\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\ne\r\ne\r\na\r\na\r\na\r\na\r\na\r\n', 'output': ['abba\r\n']}, {'input': '1 1\r\nbug\r\nsuy\r\nluh\r\ngut\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nam\r\nat\r\nan\r\nag\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\na\r\ne\r\ne\r\na\r\na\r\na\r\na\r\n', 'output': ['aabb\r\n']}, {'input': '1 4\r\naieoabcd\r\naeioabcd\r\naoeiabcd\r\naoieabcd\r\n', 'output': ['NO\r\n']}, {'input': '1 2\r\naec\r\naed\r\naek\r\naem\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nar\r\nab\r\nak\r\naz\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\na\r\na\r\na\r\na\r\nb\r\nb\r\nb\r\n', 'output': ['NO\r\n']}]


[{'input': '6 10\r\nalloc 5\r\nalloc 3\r\nerase 1\r\nalloc 6\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\n']}, {'input': '6 1\r\ndefragment\r\nalloc 10\r\nalloc 1\r\nerase -1\r\nerase 1\r\nerase 1\r\n', 'output': ['NULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '14 100\r\nalloc 99\r\nalloc 1\r\nalloc 1\r\nerase 2\r\nalloc 1\r\nerase 4\r\nerase 1\r\nalloc 100\r\nalloc 1\r\nalloc 99\r\ndefragment\r\nerase 4\r\nalloc 100\r\nalloc 99\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n4\r\nNULL\r\nNULL\r\nNULL\r\n']}, {'input': '26 25\r\ndefragment\r\nerase 1\r\nerase -1560200883\r\nalloc 44\r\ndefragment\r\nalloc 75\r\nalloc 22\r\ndefragment\r\nerase 4\r\ndefragment\r\nalloc 57\r\nalloc 53\r\nerase 4\r\nerase -1639632026\r\nerase -2121605039\r\nerase 3\r\nalloc 51\r\nalloc 65\r\ndefragment\r\nerase 2\r\nerase 4\r\nalloc 52\r\nerase 3\r\ndefragment\r\nerase -1842529282\r\nerase 3\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '22 9\r\nerase 1\r\nalloc 6\r\nalloc 65\r\nerase 1\r\nalloc 87\r\nerase -1638927047\r\nalloc 5\r\nerase 2\r\nalloc 70\r\ndefragment\r\nalloc 20\r\nalloc 48\r\nerase -69401977\r\nalloc 20\r\ndefragment\r\nerase 7\r\ndefragment\r\nerase 9\r\nerase 7\r\nerase 4\r\ndefragment\r\nalloc 66\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '12 40\r\nerase 1\r\nalloc 21\r\nalloc 5\r\nalloc 7\r\ndefragment\r\ndefragment\r\nerase 2\r\nalloc 83\r\nerase 4\r\ndefragment\r\nalloc 59\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\n2\r\n3\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '38 18\r\nalloc 72\r\nerase 2\r\nalloc 50\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 43\r\nalloc 41\r\ndefragment\r\ndefragment\r\nalloc 26\r\nalloc 46\r\nalloc 16\r\nalloc 15\r\ndefragment\r\ndefragment\r\nalloc 95\r\nerase 7\r\nerase 7\r\nerase 5\r\nerase 2\r\nerase 9\r\nerase 7\r\nalloc 43\r\ndefragment\r\nerase 7\r\ndefragment\r\nalloc 48\r\nalloc 77\r\nerase 10\r\nerase 11\r\nalloc 16\r\nalloc 84\r\nerase 1\r\ndefragment\r\nalloc 86\r\ndefragment\r\nerase 13\r\n', 'output': ['NULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nNULL\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '37 74\r\nalloc 11\r\ndefragment\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 90\r\nerase 3\r\nerase 2\r\nerase 3\r\nerase 1\r\nerase 1\r\nalloc 38\r\nalloc 19\r\nerase 1\r\nerase 3\r\ndefragment\r\nalloc 93\r\nerase 5\r\nerase 4\r\nalloc 66\r\nalloc 71\r\nerase 5\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 7\r\nalloc 47\r\nerase -95616683\r\nerase 2\r\nalloc 28\r\nalloc 32\r\nerase 11\r\nalloc 50\r\ndefragment\r\ndefragment\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\n5\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 49\r\nerase -751005193\r\ndefragment\r\nalloc 37\r\nalloc 82\r\nerase 3\r\nerase 1\r\nalloc 80\r\nalloc 51\r\ndefragment\r\nalloc 74\r\nerase 1\r\nalloc 91\r\ndefragment\r\ndefragment\r\nalloc 98\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '42 98\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 5\r\nalloc 66\r\ndefragment\r\nerase 3\r\nalloc 53\r\ndefragment\r\nerase 4\r\nerase 2\r\nalloc 70\r\nerase 3\r\ndefragment\r\ndefragment\r\nerase 2\r\nerase 3\r\nerase -1327931832\r\nalloc 93\r\nalloc 64\r\nerase 7\r\nerase 6\r\nerase 3\r\nalloc 61\r\nalloc 12\r\nalloc 65\r\nerase 2\r\nalloc 46\r\nerase 11\r\nerase 9\r\nerase 9\r\nerase 6\r\nalloc 2\r\nalloc 78\r\ndefragment\r\nerase 13\r\nerase 6\r\nerase 10\r\nalloc 53\r\nalloc 46\r\n', 'output': ['1\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '19 46\r\nalloc 21\r\nerase 2\r\nerase 1\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nalloc 40\r\nerase 1\r\ndefragment\r\ndefragment\r\nalloc 68\r\nerase -388966015\r\nalloc 85\r\nalloc 53\r\nerase 4\r\ndefragment\r\nalloc 49\r\nalloc 88\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '44 46\r\nalloc 28\r\nalloc 36\r\ndefragment\r\nerase -937404236\r\nalloc 71\r\ndefragment\r\nalloc 81\r\nalloc 51\r\nerase 3\r\ndefragment\r\nalloc 48\r\nerase 1\r\ndefragment\r\nalloc 36\r\ndefragment\r\ndefragment\r\nerase 1\r\ndefragment\r\ndefragment\r\nerase -1173350787\r\nalloc 94\r\nerase 5\r\ndefragment\r\nerase 9\r\nalloc 98\r\nerase 7\r\ndefragment\r\nerase 5\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nerase 4\r\ndefragment\r\nerase 9\r\nalloc 8\r\ndefragment\r\nerase 9\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 1\r\nalloc 70\r\nerase 9\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '26 25\r\nalloc 25\r\nerase 1\r\nalloc 24\r\nerase 2\r\nalloc 23\r\nerase 3\r\nalloc 24\r\nerase 4\r\nalloc 24\r\nerase 5\r\nalloc 21\r\nerase 6\r\nalloc 24\r\nerase 7\r\nalloc 25\r\nerase 8\r\nalloc 25\r\nerase 9\r\nalloc 24\r\nerase 10\r\nalloc 25\r\nerase 11\r\nalloc 25\r\nerase 12\r\nalloc 25\r\nerase 13\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n']}, {'input': '22 9\r\nalloc 9\r\nerase 1\r\nalloc 9\r\nerase 2\r\nalloc 9\r\nerase 3\r\nalloc 9\r\nerase 4\r\nalloc 9\r\nerase 5\r\nalloc 9\r\nerase 6\r\nalloc 9\r\nerase 7\r\nalloc 9\r\nerase 8\r\nalloc 9\r\nerase 9\r\nalloc 9\r\nerase 10\r\nalloc 9\r\nerase 11\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n']}, {'input': '7 6\r\nalloc 1\r\nalloc 2\r\nalloc 3\r\nerase 1\r\ndefragment\r\nerase 3\r\nalloc 4\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n']}, {'input': '3 1\r\nerase -1\r\nerase 0\r\nerase -2147483648\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '7 100\r\nalloc 100\r\nerase 2147483647\r\nerase 1\r\nalloc 50\r\nalloc 50\r\nerase 3\r\nerase -2147483648\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '12 10\r\nalloc 6\r\nalloc 2\r\nerase 1\r\nalloc 4\r\nalloc 2\r\nerase 3\r\nalloc 2\r\nalloc 3\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\nNULL\r\n6\r\n7\r\n8\r\n9\r\n']}, {'input': '8 50\r\nalloc 51\r\ndefragment\r\nalloc 100\r\ndefragment\r\nerase 1\r\nalloc 50\r\ndefragment\r\nalloc 50\r\n', 'output': ['NULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\n']}, {'input': '10 10\r\nalloc 10\r\nerase -1\r\nerase 1\r\nalloc 5\r\nerase -1\r\nalloc 5\r\nerase 0\r\nalloc 5\r\nerase 0\r\nalloc 5\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\n4\r\n']}]


<?php
class INPUT_HELP{
    public function read_array(){
        $a[0] = '';
        $j = 0;
        $input = fgets(STDIN);
        for ($i = 0; $i < strlen($input); $i++){
            if (preg_replace("/[0-9A-zА-я._-]/",null,$input[$i]) == false) {
                $a[$j] = $a[$j].$input[$i];
            } else {
                if ($a[$j] != '') {
                    ++$j;
                    $a[$j] = '';
                }
            }
        }
        return $a;
    }
    public function read_one(){
        $array = $this->read_array();
        return $array[0];
    }
}
?>
<?php
    $input_connect = new INPUT_HELP();
    $n = $input_connect->read_one();
    $a = $input_connect->read_array();
    for ($i = 0; $i < $n; $i++) {
        $num[$i] = $i;
    }
    for ($i = $n; $i < 2 * $n; $i++){
        $a[$i] = $a[$i - $n];
        $num[$i] = $num[$i - $n];
    }
    $h = -1;
    for ($j = 1; $j < $n; $j++){
        if ($n % $j != 0 || $n / $j < 3) continue;
        ++$h;
        $div[$h] = $j;
    }
    for ($i = 0; $i < $n; $i++){
        if ($a[$i] == 0) continue;
        for ($j = 0; $j <= $h; $j++){
            $k = $i + $div[$j];
            while ($a[$k] == 1 && $num[$k] != $i) $k += $div[$j];
            if ($num[$k] == $i) {
                echo "YES";
                die(0);
            }
        }
    }
    echo "NO";
?>


<?php

list($n, $k) = explode(" ", fgets(STDIN));
list($s) = explode(" ", fgets(STDIN));
$n = (int) $n;
$k = (int) $k;
$ansl = (int) 0;
$ansr = (int) $n - 2;

while($ansr > $ansl)
{
    $intv = (int) (($ansl + $ansr) / 2);
    $r = $k - 1;

    for($i = 0; $i < $n - 1;)
    {
        $pos = -1;

        for($j = min($i + $intv + 1, $n - 1); $j >= $i + 1; --$j)
        if($s[$j] == '0')
        {
            $pos = $j;
            break;
        }

        if($pos == -1 || $r == 0)
        {
            $pos = -1;
            break;
        }
        else
        {
            --$r;
            $i = $pos;
        }
    }

    if($pos != -1)
        $ansr = $intv;
    else
        $ansl = $intv + 1;
}

echo $ansr;

?>


<?php
    //$handle = @fopen("input.txt", "r");
    list($n, $max, $reg) = explode(' ', trim(fgets(STDIN)));

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

    $cur = $max;
    $sum = 0;
    $sec = 0;
    $spells = 0;

    while (true) {
        $cur -= $sum;
        $cur += $reg;
        $cur = min($max, $cur);
        if ($cur <= 0) {
            break;
        }
        $mpos = 0;
        $mmax = 0;
        $mpow = 0;
        for ($i = 0; $i < $n; $i++) {
            if ((double)($spell[$i][0]) >= (double)((100 * $cur / $max))
                    && $spell[$i][1] > $mmax
                    && !isset($spell[$i][2])) {
                $mmax = $spell[$i][1];
                $mpos = $i;
                $mpow = $spell[$i][0];
            }
        }

        if ($mpow == 0 && $sum <= $reg) {
            echo 'NO';
            return;
        } else if ($mpow != 0) {
            $result[$spells][0] = $sec;
            $result[$spells][1] = $mpos + 1;
            $spells++;
            $spell[$mpos][2] = $sec;
            $sum += $mmax;
        }
        $sec++;
    }

    echo "YES\n";
    echo "$sec $spells\n";
    for ($i = 0; $i < count($result); $i++) {
        echo "{$result[$i][0]} {$result[$i][1]}\n";
    }


use std::io;
use std::io::Write;

fn main() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    let mut input_iter = input.trim().split_whitespace();
    let _n = input_iter.next();
    let mut k = input_iter.next().unwrap().parse::<usize>().unwrap();

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    let mut s = input.trim().bytes().map(|x| x - '0' as u8).collect::<Vec<u8>>();

    if k != 0 {
        let mut start = 0;
        if s.len() > 1 {
            start = 1;
            if s[0] != 1 {
                s[0] = 1;
                k -= 1;
            }
        }

        if k != 0 {
            for d in start..s.len() {
                if s[d] != 0 {
                    s[d] = 0;
                    k -= 1;
                    if k == 0 {
                        break;
                    }
                }
            }
        }
    }

    let out = std::io::stdout();
    let mut buf = std::io::BufWriter::new(out.lock());

    for d in s.iter() {
        write!(buf, "{}", d);
    }
    writeln!(buf, "");
}


use std::io;
use std::str::FromStr;

struct LuckyNum{
    n4: usize,
    n7: usize,
}
impl LuckyNum{
    fn new(n4: usize, n7: usize) -> LuckyNum{
        LuckyNum { n4, n7 }
    }
    fn len(&self) -> usize{
        self.n4 + self.n7
    }
    fn digit_sum(&self) -> usize{
        self.n4 * 4 + self.n7 * 7
    }
    fn less_than(&self, other: &LuckyNum) -> bool{
        if self.len() < other.len(){
            true
        }
        else if self.len() > other.len(){
            false
        }
        else{
            self.n4 > other.n4
        }
    }
    fn to_string(&self) -> String{
        let mut res = "4".repeat(self.n4);
        res.push_str("7".repeat(self.n7).as_str());
        res
    }
}
fn main(){
    let n: usize = input();
    let mut ans = LuckyNum::new(n, n);
    for n4 in 0..=n/4{
        let n7 = (n - n4 * 4) / 7;
        let lucky_num = LuckyNum::new(n4, n7);
        if lucky_num.digit_sum() == n && lucky_num.less_than(&ans){
            ans = lucky_num;
        }
    }
    if ans.digit_sum() == n{
        println!("{}", ans.to_string());
    }
    else{
        println!("-1");
    }
}

fn input<T>() -> T
    where
        T: FromStr,
        <T as FromStr>::Err: std::fmt::Debug,
{
    let mut n = String::new();
    io::stdin()
        .read_line(&mut n)
        .expect("failed to read from stdin");
    n.trim().parse::<T>().expect("parsing error")
}

fn input_line<T>() -> Vec<T>
    where
        T: FromStr,
        <T as FromStr>::Err: std::fmt::Debug,
{
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("Failed to read line");
    let mut inputs: Vec<T> = line.trim().split(" ")
        .map(|x| x.parse::<T>().expect("parsing error"))
        .collect();
    inputs
}
//      IIIIIIIII      OOOOO             A          NN        N    EEEEEEEEEE
//          I         O     O           A A         N N       N    E
//          I        O       O         A   A        N  N      N    E
//          I        O       O        A     A       N   N     N    E
//          I        O       O       AAAAAAAAA      N    N    N    EEEEEEEE
//          I        O       O      A         A     N     N   N    E
//          I        O       O     A           A    N      N  N    E
//          I         O     O     A             A   N       N N    E
//      IIIIIIIII      OOOOO     A               A  N        NN    EEEEEEEEEE ___ KAPANADZE


struct Scanner<R> {
    reader: R,
    line: Vec<u8>,
    ptr: usize

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        Self{reader, line: vec![], ptr: 0}
    }

    fn scan<T: std::str::FromStr>(&mut self) -> T {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                let start = self.ptr;
                while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {
                    self.ptr += 1;
                }
                return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().
                    expect("parse error");
            }
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
    }

    fn line(&mut self) -> Vec<u8> {
        if self.ptr == self.line.len() {
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
        let result = self.line[self.ptr..].to_vec();
        self.ptr = self.line.len();
        return result;
    }

    fn eof(&mut self) -> bool {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                return false;
            }
            self.line.clear();
            self.ptr = 0;
            if let Ok(0) = self.reader.read_until(b'\n', &mut self.line) {
                return true;
            }
        }
    }

}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let p1: i64 = scanner.scan();
    let p2: i64 = scanner.scan();
    let p3: i64 = scanner.scan();
    let t1: i64 = scanner.scan();
    let t2: i64 = scanner.scan();
    let l: i64 = scanner.scan();
    let r: i64 = scanner.scan();
    let mut result: i64 = (r - l) * p1;
    let mut last: i64 = r;
    for _ in 1..n {
        let l: i64 = scanner.scan();
        let r: i64 = scanner.scan();
        result += (r - l) * p1 + (l - last).max(0) * p1 + (l - last - t1).max(0) * (p2 - p1)
            + (l - last - t1 - t2).max(0) * (p3 - p2);
        last = r;
    }
    writeln!(writer, "{}", result).unwrap();
}

fn main() {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    let mut writer = std::io::BufWriter::new(stdout.lock());
    let mut scanner = Scanner::new(stdin.lock());
    let tests: usize = 1;
    for _ in 0..tests {
        solve(&mut scanner, &mut writer);
    }
}


use std::{collections::HashSet, io::BufRead};

/**
 * A. Letter
 * time limit per test: 1 second
 * memory limit per test: 64 megabytes
 * input: standard input
 * output: standard output
 *
 * A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded
 * some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives
 * in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he
 * wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it
 * is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum
 * cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.
 *
 * Input
 * The first line of the input data contains numbers n and m (1ââ¤ân,âmââ¤â50), n â amount of lines, and m â amount of columns
 * on Bob's sheet. The following n lines contain m characters each. Character Â«.Â» stands for a non-shaded square on the
 * sheet, and Â«*Â» â for a shaded square. It is guaranteed that Bob has shaded at least one square.
 *
 * Output
 * Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output
 * format better.
 *
 * Examples
 *   Input
 *   6 7
 *   .......
 *   ..***..
 *   ..*....
 *   ..***..
 *   ..*....
 *   ..***..
 *
 *   Output
 *   ***
 *   *..
 *   ***
 *   *..
 *   ***
 *
 *   Input
 *   3 3
 *   ***
 *   *.*
 *   ***
 *
 *   Output
 *   ***
 *   *.*
 *   ***
 */
fn main() {
    let stdin = std::io::stdin();
    let mut lines = stdin.lock().lines();

    let first_line = lines.next().unwrap().unwrap();
    let (n, m) = first_line.split_once(' ').unwrap();
    let (n, m): (usize, usize) = (n.parse().unwrap(), m.parse().unwrap());

    let grid: HashSet<(usize, usize)> = lines
        .take(n)
        .map(Result::unwrap)
        .enumerate()
        .flat_map(|(y, line)| {
            line.chars()
                .take(m)
                .enumerate()
                .filter(|&(_, ch)| ch == '*')
                .map(|(x, _)| (x, y))
                .collect::<Vec<_>>()
        })
        .collect();

    let min_x = *grid.iter().map(|(x, _)| x).min().unwrap();
    let max_x = *grid.iter().map(|(x, _)| x).max().unwrap();
    let min_y = *grid.iter().map(|(_, y)| y).min().unwrap();
    let max_y = *grid.iter().map(|(_, y)| y).max().unwrap();

    for y in min_y..=max_y {
        for x in min_x..=max_x {
            if grid.contains(&(x, y)) {
                print!("*");
            } else {
                print!(".");
            }
        }

        println!();
    }
}


struct Scanner<R> {
    reader: R,
    line: Vec<u8>,
    ptr: usize

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        Self{reader, line: vec![], ptr: 0}
    }

    fn scan<T: std::str::FromStr>(&mut self) -> T {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                let start = self.ptr;
                while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {
                    self.ptr += 1;
                }
                return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().
                    expect("parse error");
            }
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
    }

    fn line(&mut self) -> Vec<u8> {
        if self.ptr == self.line.len() {
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
        let result = self.line[self.ptr..].to_vec();
        self.ptr = self.line.len();
        return result;
    }

    fn eof(&mut self) -> bool {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                return false;
            }
            self.line.clear();
            self.ptr = 0;
            if let Ok(0) = self.reader.read_until(b'\n', &mut self.line) {
                return true;
            }
        }
    }

}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let mut q: Vec<(usize, usize)> = (0..n).map(|id| (scanner.scan(), id)).collect();
    let m: usize = scanner.scan();
    let mut gr_inv = vec![Vec::new(); n];
    for _ in 0..m {
        let a = scanner.scan::<usize>() - 1;
        let b = scanner.scan::<usize>() - 1;
        let c: i64 = scanner.scan();
        gr_inv[b].push((c, a));
    }
    q.sort_unstable();
    q.reverse();
    for row in &mut gr_inv {
        row.sort_unstable();
    }
    let mut result = 0;
    let mut used = vec![false; n];
    used[q[0].1] = true;
    for i in 1..n {
        let mut ok = false;
        for &(val, id) in &gr_inv[q[i].1] {
            if used[id] {
                result += val;
                used[q[i].1] = true;
                ok = true;
                break;
            }
        }
        if !ok {
            result = -1;
            break;
        }
    }
    writeln!(writer, "{}", result).unwrap();
}

fn main() {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    let mut writer = std::io::BufWriter::new(stdout.lock());
    let mut scanner = Scanner::new(stdin.lock());
    let tests: usize = 1;
    for _ in 0..tests {
        solve(&mut scanner, &mut writer);
    }
}


use std::io::{self, Read};

macro_rules! next {
	($x:expr) => {{ $x.next().unwrap().parse().unwrap() }};
}

fn main() {
	let mut inp = String::new();
	io::stdin().read_to_string(&mut inp).unwrap();
	let mut inp = inp.split_whitespace();
	let n: usize = next!(inp);
	let v: Vec<i32> = (1..n).map(|_| next!(inp)).collect();
	let a: usize = next!(inp);
	let b: usize = next!(inp);
	let y: i32 = (a..b).map(|i| v[i - 1]).sum();
	println!("{}", y);
}


struct Scanner<R> {
    reader: R,
    line: Vec<u8>,
    ptr: usize

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        Self{reader, line: vec![], ptr: 0}
    }

    fn scan<T: std::str::FromStr>(&mut self) -> T {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                let start = self.ptr;
                while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {
                    self.ptr += 1;
                }
                return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().
                    expect("parse error");
            }
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
    }

    fn line(&mut self) -> Vec<u8> {
        if self.ptr == self.line.len() {
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
        let result = self.line[self.ptr..].to_vec();
        self.ptr = self.line.len();
        return result;
    }

    fn eof(&mut self) -> bool {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                return false;
            }
            self.line.clear();
            self.ptr = 0;
            if let Ok(0) = self.reader.read_until(b'\n', &mut self.line) {
                return true;
            }
        }
    }

}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let mut set = std::collections::BTreeSet::new();
    for _ in 0..n {
        let a: String = scanner.scan();
        let b: String = scanner.scan();
        set.insert(a + " " + &b);
    }
    writeln!(writer, "{}", set.len()).unwrap();
}

fn main() {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    let mut writer = std::io::BufWriter::new(stdout.lock());
    let mut scanner = Scanner::new(stdin.lock());
    let tests: usize = 1;
    for _ in 0..tests {
        solve(&mut scanner, &mut writer);
    }
}

[{'input': ['5\r\nbirch yellow\r\nmaple red\r\nbirch yellow\r\nmaple yellow\r\nmaple green\r\n'], 'output': ['4\r\n']}, {'input': ['3\r\noak yellow\r\noak yellow\r\noak yellow\r\n'], 'output': ['1\r\n']}, {'input': ['5\r\nxbnbkzn hp\r\nkaqkl vrgzbvqstu\r\nj aqidx\r\nhos gyul\r\nwefxmh tygpluae\r\n'], 'output': ['5\r\n']}, {'input': ['1\r\nqvwli hz\r\n'], 'output': ['1\r\n']}, {'input': ['4\r\nsrhk x\r\nsrhk x\r\nqfoe vnrjuab\r\nqfoe vnrjuab\r\n'], 'output': ['2\r\n']}, {'input': ['4\r\nsddqllmmpk syded\r\nfprsq fnenjnaz\r\nn hdej\r\nsddqllmmpk syded\r\n'], 'output': ['3\r\n']}, {'input': ['17\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\n'], 'output': ['1\r\n']}, {'input': ['18\r\nb d\r\nrfdb esp\r\nrfdb esp\r\nb d\r\nrfdb esp\r\nrfdb esp\r\nb d\r\nb d\r\nrfdb esp\r\nrfdb esp\r\nb d\r\nrfdb esp\r\nb d\r\nrfdb esp\r\nb d\r\nb d\r\nrfdb esp\r\nrfdb esp\r\n'], 'output': ['2\r\n']}, {'input': ['13\r\nsvpzwtwn rykzfdce\r\nqweiyeck jkreouy\r\nhk nnli\r\ntwxrnbbdt vtuv\r\nxokqjtylly sz\r\nesdt dbfidjslq\r\ng ybqgomvw\r\nxcpfjmf zcqvz\r\nifajadhj invzueip\r\nvdemdnxifb hckwebmi\r\nsdpnhipam wvowzavh\r\nuqdlfskhgo vunbpghae\r\ne dtigwnb\r\n'], 'output': ['13\r\n']}, {'input': ['20\r\nm vkfh\r\nvptikamead mvx\r\nitu mf\r\nklruxckw aqega\r\nekqkd enjllwol\r\ncc uybfdh\r\nimrfdngvo u\r\ne uh\r\ntwt jsslcfuogk\r\nbljwqsag tuqbdn\r\nqcv q\r\nasx gzhvwwmajj\r\nqcv q\r\nekqkd enjllwol\r\nasx gzhvwwmajj\r\nks vv\r\nkzyfi cn\r\ncc uybfdh\r\nitu mf\r\ncjbjhtbyvk vatwfmux\r\n'], 'output': ['15\r\n']}, {'input': ['2\r\nab ab\r\na bab\r\n'], 'output': ['2\r\n']}]


fn main() {
    let (n,m): (usize,usize) = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };

    let mut ans=vec![0;n+1];

    for _ in 0..m{
        let (x,y): (usize,usize) = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            (
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };

        for j in x..y+1{
            ans[j]+=1;
        }
    }

    let mut flag=0;

    for i in 1..n+1{
        if ans[i]!=1{
            println!("{} {}",i,ans[i]);
            flag=1;
            break;
        }
    }

    if flag==0{
        println!("OK");
    }

}


struct Scanner<R> {
    reader: R,
    line: Vec<u8>,
    ptr: usize

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        Self{reader, line: vec![], ptr: 0}
    }

    fn scan<T: std::str::FromStr>(&mut self) -> T {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                let start = self.ptr;
                while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {
                    self.ptr += 1;
                }
                return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().
                    expect("parse error");
            }
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
    }

    fn line(&mut self) -> Vec<u8> {
        if self.ptr == self.line.len() {
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
        let result = self.line[self.ptr..].to_vec();
        self.ptr = self.line.len();
        return result;
    }

    fn eof(&mut self) -> bool {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                return false;
            }
            self.line.clear();
            self.ptr = 0;
            if let Ok(0) = self.reader.read_until(b'\n', &mut self.line) {
                return true;
            }
        }
    }

}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let mut ptr = 0;
    for i in 1..n {
        ptr = (ptr + i) % n;
        write!(writer, "{} ", ptr + 1).unwrap();
    }
    writeln!(writer).unwrap();
}

fn main() {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    let mut writer = std::io::BufWriter::new(stdout.lock());
    let mut scanner = Scanner::new(stdin.lock());
    let tests: usize = 1;
    for _ in 0..tests {
        solve(&mut scanner, &mut writer);
    }
}


use std::io;

fn main() {
    let mut buf = String::new();
    let mut n: usize = 0;
    let reader = io::stdin();
    reader.read_line(&mut buf);
    n = buf.trim().parse()
            .expect(" ");
    let mut v = vec![0;n-1];

    let mut buf2 = String::new();
    reader.read_line(&mut buf2);
    let it = buf2.trim().split(" ");
    let mut ct = 0;
    for sub in it{
        v[ct] = sub.trim().parse()
            .expect(" ");
        ct += 1;
    }

    let mut buf3 = String::new();
    reader.read_line(&mut buf3);
    let wv = buf3.trim().split(" ").collect::<Vec<&str>>();
    let a:i32 =  wv[0].parse().expect(" ");
    let b:i32 =  wv[1].parse().expect(" ");
    let mut ans: u32 = 0;
    for i in (a-1)..=(b-2){
        ans += v[i as usize];
    }
    println!("{}",ans);
}


// mod scanner;
// use scanner::Scanner;
use std::io::{self, prelude::*};
use std::str;
pub struct Scanner<R> {
    reader: R,
    buffer: Vec<String>,
}

impl<R: io::BufRead> Scanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buffer: vec![],
        }
    }

    /// Use "turbofish" syntax token::<T>() to select data type of next token.
    ///
    /// # Panics
    ///
    /// Panics if there's an I/O error or if the token cannot be parsed as T.
    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());
    let n: usize = scan.token();
    let mut partial_sum = vec![0, 0, 0];
    for _ in 0..n {
        let vector: Vec<isize> = (0..3).map(|_| scan.token()).collect();
        partial_sum[0] = partial_sum[0] + vector[0];
        partial_sum[1] = partial_sum[1] + vector[1];
        partial_sum[2] = partial_sum[2] + vector[2];
    }
    if partial_sum[0] != 0 || partial_sum[1] != 0 || partial_sum[2] != 0 {
        write!(out, "NO").ok();
    } else {
        write!(out, "YES").ok();
    }
}


use std::{io, str::FromStr};

fn input<T: FromStr>() -> Result<T, <T as std::str::FromStr>::Err> {
    let mut s: String = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().parse()
}
fn main() {
    let line_count: usize = input().unwrap();

    for _ in 0..line_count {
        let word: String = input().unwrap();
        if word.len() <= 10 {
            println!("{word}");
        } else {
            println!(
                "{}{}{}",
                word.chars().nth(0).unwrap(),
                word.len() - 2,
                word.chars().nth_back(0).unwrap()
            );
        }
    }
}


struct Scanner<R> {
    reader: R,
    line: Vec<u8>,
    ptr: usize

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        Self{reader, line: vec![], ptr: 0}
    }

    fn scan<T: std::str::FromStr>(&mut self) -> T {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                let start = self.ptr;
                while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {
                    self.ptr += 1;
                }
                return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().
                    expect("parse error");
            }
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
    }

    fn line(&mut self) -> Vec<u8> {
        if self.ptr == self.line.len() {
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
        let result = self.line[self.ptr..].to_vec();
        self.ptr = self.line.len();
        return result;
    }

    fn eof(&mut self) -> bool {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                return false;
            }
            self.line.clear();
            self.ptr = 0;
            if let Ok(0) = self.reader.read_until(b'\n', &mut self.line) {
                return true;
            }
        }
    }

}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let m: usize = scanner.scan();
    let k: usize = scanner.scan();
    let t: usize = scanner.scan();
    let mut sets = vec![Vec::new(); n];
    let mut counts = vec![m; n];
    for _ in 0..k {
        let a = scanner.scan::<usize>() - 1;
        let b = scanner.scan::<usize>() - 1;
        sets[a].push(b);
        counts[a] -= 1;
    }
    let mut ps = vec![0; n + 1];
    for i in 0..n {
        ps[i + 1] = ps[i] + counts[i];
        sets[i].sort_unstable();
    }
    let names = ["Carrots", "Kiwis", "Grapes"];
    for _ in 0..t {
        let i = scanner.scan::<usize>() - 1;
        let j = scanner.scan::<usize>() - 1;
        if let Err(ptr) = sets[i].binary_search(&j) {
            let id = ps[i] + j - ptr;
            writeln!(writer, "{}", names[id % 3]).unwrap();
        } else {
            writeln!(writer, "Waste").unwrap();
        }
    }
}

fn main() {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    let mut writer = std::io::BufWriter::new(stdout.lock());
    let mut scanner = Scanner::new(stdin.lock());
    let tests: usize = 1;
    for _ in 0..tests {
        solve(&mut scanner, &mut writer);
    }
}


use std::io;
use std::io::Write;

/**************************************************

    START OF TEMPLATE CODE

 *************************************************/
#[allow(unused_macros)]
macro_rules! dbg {
    ($first_val:expr, $($val:expr),+ $(,)?) => {
        eprint!("[{}:{}] {} = {:?}",
                    file!(), line!(), stringify!($first_val), &$first_val);
        ($(eprint!(", {} = {:?}", stringify!($val), &$val)),+,);
        eprintln!();
    };
    ($first_val:expr) => {
        eprintln!("[{}:{}] {} = {:?}",
                    file!(), line!(), stringify!($first_val), &$first_val);
    };
}

enum InputSource {
    Stdin,
    FromFile(Vec<String>),
}

struct Scanner {
    buffer: Vec<String>,
    input_source: InputSource,
}

impl Scanner {
    #[allow(dead_code)]
    fn new() -> Self {
        Self { buffer: vec![], input_source: InputSource::Stdin }
    }

    #[allow(dead_code)]
    fn new_file(filename: &str) -> Self {
        let file = std::fs::read_to_string(filename).unwrap();
        let mut lines: Vec<String> = file.lines().map(|line| String::from(line)).collect();
        lines.reverse();
        Self { buffer: vec![], input_source: InputSource::FromFile(lines) }
    }

    #[allow(dead_code)]
    fn i64(&mut self) -> i64 {
        self.next::<i64>()
    }

    #[allow(dead_code)]
    fn i32(&mut self) -> i32 {
        self.next::<i32>()
    }

    #[allow(dead_code)]
    fn usize(&mut self) -> usize {
        self.next::<usize>()
    }

    #[allow(dead_code)]
    fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next::<T>()).collect()
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            match &mut self.input_source {
                | InputSource::Stdin => { std::io::stdin().read_line(&mut input).expect("Failed read"); }
                | InputSource::FromFile(lines) => {
                    let line = lines.pop().unwrap();
                    input = line;
                }
            }

            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }

    #[allow(dead_code)]
    fn string(&mut self) -> Vec<u8> {
        self.next::<String>().into_bytes()
    }
}

/**************************************************

    END OF TEMPLATE CODE

 *************************************************/

fn build(s: &[u8], it: &mut usize, graph: &mut Vec<Vec<usize>>, nodes: &mut Vec<usize>, l: usize, r: usize) -> bool {
    if r - l <= 1 {
        return true;
    }
    let m = (l + r) >> 1;
    if !build(s, it, graph, nodes, l, m) {
        return false;
    }
    if !build(s, it, graph, nodes, m, r) {
        return false;
    }
    let mut i = l;
    let mut j = m;
    let mut b = vec![];
    while i < m && j < r {
        if *it == s.len() {
            return false;
        }
        if s[*it] == b'0' {
            graph[nodes[i]].push(nodes[j]);
            b.push(nodes[i]);
            i += 1;
        } else if s[*it] == b'1' {
            graph[nodes[j]].push(nodes[i]);
            b.push(nodes[j]);
            j += 1;
        } else {
            unreachable!();
        }
        *it += 1;
    }
    while i < m {
        b.push(nodes[i]);
        i += 1;
    }
    while j < r {
        b.push(nodes[j]);
        j += 1;
    }
    for (idx, &val) in b.iter().enumerate() {
        nodes[idx + l] = val;
    }
    true
}

pub fn main() {
    let stdout = io::stdout();
    let mut out = std::io::BufWriter::new(stdout.lock());
    let mut sc = Scanner::new();

    let s = sc.string();
    let mut left = 0;
    let mut right = 100_005;
    while right - left > 1 {
        let n = (left + right) >> 1;

        let mut graph = vec![vec![]; n];
        let mut it = 0;
        let mut nodes = (0..n).collect();
        if !build(&s, &mut it, &mut graph, &mut nodes, 0, n) {
            right = n;
        } else {
            if it == s.len() {
                writeln!(out, "{}", n).unwrap();
                let mut res = vec![0; n];
                for (idx, node) in nodes.iter().enumerate() {
                    res[*node] = idx + 1;
                }
                for r in &res {
                    write!(out, "{} ", r).unwrap();
                }
                return;
            }
            left = n;
        }
    }
    unreachable!();
}


use std::io::Read;

fn input(read_file: bool) -> String {
    if read_file {
        let mut file = std::fs::File::open("sample.txt").unwrap();
        let mut buf = String::new();
        file.read_to_string(&mut buf).unwrap();
        buf
    } else {
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf).unwrap();
        buf.trim_end().to_owned()
    }
}

fn solve(ws: &mut std::str::SplitWhitespace) {
    let n: usize = ws.next().unwrap().parse().unwrap();
    let points: Vec<(i32, i32)> = (0..n)
        .map(|_| {
            (
                ws.next().unwrap().parse().unwrap(),
                ws.next().unwrap().parse().unwrap(),
            )
        })
        .collect();

    let mut visited = vec![false; n];
    let mut q = std::collections::VecDeque::new();

    let mut ans = 0;
    for i in 0..n {
        if visited[i] {
            continue;
        }
        q.push_back(points[i]);
        visited[i] = true;
        while !q.is_empty() {
            let p = q.pop_front().unwrap();
            for j in 0..n {
                if points[j] == p {
                    visited[j] = true;
                    continue;
                }
                if visited[j] {
                    continue;
                }
                if p.0 == points[j].0 {
                    q.push_back(points[j]);
                } else if p.1 == points[j].1 {
                    q.push_back(points[j]);
                }
            }
        }
        ans += 1;
    }

    println!("{}", ans - 1);
}

fn main() {
    const READ_FROM_FILE: bool = false;

    let s = input(READ_FROM_FILE);
    let mut ws = s.split_whitespace();

    solve(&mut ws);
    // let t = ws.next().unwrap().parse().unwrap();
    // for _ in 0..t {}
}


struct Scanner<R> {
    reader: R,
    line: Vec<u8>,
    ptr: usize

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        Self{reader, line: vec![], ptr: 0}
    }

    fn scan<T: std::str::FromStr>(&mut self) -> T {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                let start = self.ptr;
                while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {
                    self.ptr += 1;
                }
                return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().
                    expect("parse error");
            }
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
    }

}

fn fill(mask: usize, set: &Vec<bool>, maxs: &mut Vec<u32>) -> u32 {
    if maxs[mask] != u32::MAX {
        return maxs[mask];
    }
    maxs[mask] = if set[mask] {mask.count_ones()} else {0};
    let mut tmp = mask;
    while tmp != 0 {
        let bit = (tmp & (tmp - 1)) ^ tmp;
        tmp ^= bit;
        let next = mask ^ bit;
        fill(next, set, maxs);
        maxs[mask] = maxs[mask].max(maxs[next]);
    }
    return maxs[mask];
}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let s: Vec<usize> = scanner.scan::<String>().bytes().map(|c| 1usize << (c - b'a')).collect();
    let masks = 1 << 20;
    let mut set = vec![false; masks];
    let n = s.len();
    for i in 0..n {
        let mut mask = 0;
        for j in i..n {
            if mask & s[j] != 0 {
                break;
            }
            mask |= s[j];
            set[mask] = true;
        }
    }
    let mut maxs = vec![u32::MAX; masks];
    fill(masks - 1, &set, &mut maxs);
    let mut result = 0;
    for mask in 0..masks {
        if !set[mask] {
            continue;
        }
        result = result.max(mask.count_ones() + maxs[!mask & (masks - 1)]);
    }
    writeln!(writer, "{}", result).unwrap();
}

fn main() {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    let mut writer = std::io::BufWriter::new(stdout.lock());
    let mut scanner = Scanner::new(stdin.lock());
    let tests: usize = 1;
    for _ in 0..tests {
        solve(&mut scanner, &mut writer);
    }
}

[{'input': ['abacaba\r\n'], 'output': ['3\r\n']}, {'input': ['abcdecdf\r\n'], 'output': ['6\r\n']}, {'input': ['aabbcc\r\n'], 'output': ['3\r\n']}, {'input': ['abcdeefc\r\n'], 'output': ['6\r\n']}, {'input': ['b\r\n'], 'output': ['1\r\n']}, {'input': ['bh\r\n'], 'output': ['2\r\n']}, {'input': ['rmohl\r\n'], 'output': ['5\r\n']}, {'input': ['sbkedsbhen\r\n'], 'output': ['7\r\n']}, {'input': ['boodbpmpdfrmackcrtbasatcjbbbgkkrcdmiejqpqiqqpfepinqscfcrhglqnqnehsrmljoqdtsboammreagilegamlforqsknbn\r\n'], 'output': ['16\r\n']}, {'input': ['kbceqetaboafejrbkibcbnqaildribhoggaogmfoqfcejmgcrroliqkohsmpsppsmagdthblnbjsmdcscnsfjsradgdsclaahlisehqeafjplqblaqtdermttgitbhkmeakmnjrtkosbtihlbhofallpecrremgsbrtapfdblklnapearnkrpbhqbcmrffgoneiddsacoijjtqfrqojmllopttjhrqqmcbarmnttladfrjjrhoajrrksjickadpimoajrkbgtstmnmqoocsjcscghnbgnldphfqlsrqmflchgcktlbjpmlcackgmcmmterpqkgnonklrishirhoiemscnqtisrsjptoepifcaiqhggdmfrehgroobgsfmibclorktmdknlonsalffoqkkglsfaptopoeacqdhkdqnrqcorrsfssbdcdmrhpectqictsgicnkhspoqfpptbnbhkegksgfnlppoftpitcgiatsklemgaso\r\n'], 'output': ['18\r\n']}, {'input': ['rbakamtrsr\r\n'], 'output': ['7\r\n']}, {'input': ['qnhssobqcc\r\n'], 'output': ['7\r\n']}]


fn main() {
    input!{
        n: usize,
        costs: [[usize; n]; 3],
    };

    let mut children = vec![vec![]; n];
    for _ in 1..n {
        input!{ u: usize1, v: usize1 };
        if children[u].len() >= 2 || children[v].len() >= 2 {
            println!("-1");
            return;
        }
        children[u].push(v);
        children[v].push(u);
    }

    for i in 0..n {
        if children[i].len() == 1 {
            let line = makeline(&children, i);
            let mut min = usize::MAX;
            let mut scheme = [0; 3];
            for pat in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] {
                let mut cost = 0;
                for (i, &idx) in line.iter().enumerate() {
                    cost += costs[pat[i % 3]][idx];
                }
                if cost < min {
                    min = cost;
                    scheme = pat;
                }
            }
            let mut painted = vec![0; n];
            for (i, &idx) in line.iter().enumerate() {
                painted[idx] = scheme[i % 3];
            }
            println!("{min}");
            for c in painted {
                print!("{} ", c + 1);
            }
            return;
        }
    }
}

fn makeline(tree: &[Vec<usize>], root: usize) -> Vec<usize> {
    let n = tree.len();
    let mut line = Vec::with_capacity(n);
    let (mut cur, mut fa) = (tree[root][0], root);
    line.push(fa);
    line.push(cur);

    while line.len() < n {
        let next = if tree[cur][0] == fa { tree[cur][1] } else { tree[cur][0] };
        line.push(next);
        fa = cur;
        cur = next;
    }

    line
}

mod io {
    use std::cell::RefCell;
    use std::io::*;

    std::thread_local! {
        pub static STDIN: RefCell<Stdin> = RefCell::new(stdin());
        pub static STDOUT: RefCell<BufWriter<Stdout>> = RefCell::new(BufWriter::new(stdout()));
    }

    #[macro_export]
    macro_rules! input {
        () => {};
        (mut $var:ident: $t:tt, $($rest:tt)*) => {
            let mut $var = __input_inner!($t);
            input!($($rest)*)
        };
        ($var:ident: $t:tt, $($rest:tt)*) => {
            let $var = __input_inner!($t);
            input!($($rest)*)
        };
        (mut $var:ident: $t:tt) => {
            let mut $var = __input_inner!($t);
        };
        ($var:ident: $t:tt) => {
            let $var = __input_inner!($t);
        };
    }

    #[macro_export]
    macro_rules! __input_inner {
        (($($t:tt),*)) => {
            ($(__input_inner!($t)),*)
        };
        ([$t:tt; $n:expr]) => {
            (0..$n).map(|_| __input_inner!($t)).collect::<Vec<_>>()
        };
        ([$t:tt]) => {{
            let n = __input_inner!(usize);
            (0..n).map(|_| __input_inner!($t)).collect::<Vec<_>>()
        }};
        (chars) => {
            __input_inner!(String).chars().collect::<Vec<_>>()
        };
        (bytes) => {
            __input_inner!(String).into_bytes()
        };
        (usize1) => {
            __input_inner!(usize) - 1
        };
        ($t:ty) => {
            $crate::io::STDIN.with(|r| {
                use std::io::BufRead;
                let r = r.borrow_mut();
                let mut r = r.lock();
                let mut s = vec![];
                loop {
                    let buf = r.fill_buf().unwrap();
                    if buf.is_empty() {
                        break;
                    }
                    if let Some(i) = buf.iter().position(u8::is_ascii_whitespace) {
                        s.extend_from_slice(&buf[..i]);
                        r.consume(i + 1);
                        if !s.is_empty() {
                            break;
                        }
                    } else {
                        s.extend_from_slice(buf);
                        let n = buf.len();
                        r.consume(n);
                    }
                }
                std::str::from_utf8(&s).unwrap().parse::<$t>().unwrap()
            })
        };
    }

    #[macro_export]
    macro_rules! println {
        () => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                std::writeln!(w.borrow_mut()).unwrap()
            })
        };
        ($($arg:tt)*) => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                std::writeln!(w.borrow_mut(), $($arg)*).unwrap()
            })
        };
    }

    #[macro_export]
    macro_rules! print {
        ($($arg:tt)*) => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                std::write!(w.borrow_mut(), $($arg)*).unwrap()
            })
        };
    }

    #[macro_export]
    macro_rules! flush {
        () => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                w.borrow_mut().flush().unwrap()
            })
        };
    }
}


struct Scanner<R> {
    reader: R,
    line: Vec<u8>,
    ptr: usize

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        return Self {reader, line: vec![], ptr: 0};
    }

    fn scan<T: std::str::FromStr>(&mut self) -> T {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                let start = self.ptr;
                while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {
                    self.ptr += 1;
                }
                return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().
                    expect("parse error");
            }
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
    }

}

fn solve_min(counts: &Vec<usize>) -> usize {
    let mut result = 0;
    let mut ptr = 0;
    while ptr < counts.len() {
        if counts[ptr] == 0 {
            ptr += 1;
            continue;
        }
        ptr += 3;
        result += 1;
    }
    return result;
}

fn solve_max(mut counts: Vec<usize>) -> usize {
    let mut result = 0;
    for i in 0..counts.len() {
        if let Some(v) = counts.get_mut(i.wrapping_sub(1)) {
            if *v != 0 {
                *v -= 1;
                result += 1;
                continue;
            }
        }
        if counts[i] != 0 {
            counts[i] -= 1;
            result += 1;
            continue;
        }
        if let Some(v) = counts.get_mut(i + 1) {
            if *v != 0 {
                *v -= 1;
                result += 1;
                continue;
            }
        }
    }
    return result;
}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let x: Vec<usize> = (0..n).map(|_| scanner.scan()).collect();
    let mut counts: Vec<usize> = vec![0; n + 2];
    for &x in &x {
        counts[x] += 1;
    }
    let min = solve_min(&counts);
    let max = solve_max(counts);
    writeln!(writer, "{} {}", min, max).unwrap();
}

fn main() {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    let mut writer = std::io::BufWriter::new(stdout.lock());
    let mut scanner = Scanner::new(stdin.lock());
    let tests: usize = 1;
    for _ in 0..tests {
        solve(&mut scanner, &mut writer);
    }
}


//resubmission to find cause of Runtime Error when reading input

use std::collections::HashSet;

macro_rules! stdin_to {
    ($name: ident: &str) => { let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); s = remove_linebreak(&s).to_string(); let $name = s; };
    ($name: ident: $t: ty) => { let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); s = remove_linebreak(&s).to_string(); let $name = s.parse::<$t>().unwrap(); };
}
macro_rules! stdin_to_vec {
    ($name: ident: &str, $spl: tt) => { stdin_to!(line: &str); let $name = line.split($spl).map(|s| s.to_string()).collect::<Vec<_>>(); };
    ($name: ident: $t: ty, $spl: tt) => { stdin_to!(line: &str); let $name = line.split($spl).map(|s| s.parse::<$t>().unwrap()).collect::<Vec<_>>(); };
}
fn remove_linebreak(s: &str) -> &str { s.strip_suffix("\r\n").or(s.strip_suffix("\n")).unwrap_or(s) }

fn main() {

    stdin_to!(n: usize);
    stdin_to_vec!(perm: i32, " ");
    stdin_to_vec!(favs: i32, " ");

    //let n = 7;
    //let perm = vec![4, 2, 5, 1, 3, 7, 6];
    //let favs = vec![4, 6, 6, 1, 6, 6, 1];

    let mut arr = (0..n).collect::<Vec<_>>();

    for i in 0..n {
        let val1 = i as i32 + 1;
        for j in i+1..n {
            let val2 = j as i32 + 1;
            let d = (val1-val2).abs();
            if d == favs[i] || d == favs[j] {
                //println!("join {i} {j}");
                join(i, j, &mut arr);
            }
        }
    }
    //println!("{arr:?}");

    if (0..n).all(|i| find(i, &mut arr) == find((perm[i] as i32-1) as usize, &mut arr)) {
        println!("YES");
    } else {
        println!("NO");
    }
}
fn join(a: usize, b: usize, arr: &mut Vec<usize>) {
    let a = find(a, arr);
    let b = find(b, arr);
    arr[a] = b;
}
fn find(mut x: usize, arr: &mut Vec<usize>) -> usize {
    while x != arr[x] { arr[x] = arr[arr[x]]; x = arr[x]; }
    x
}


use std::io;

fn read_line() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s.strip_suffix("\r\n").or(s.strip_suffix('\n')).unwrap_or(s.as_str()).to_string()
}
fn read_line_split(spl: &str) -> Vec<String> {
    let s = read_line();
    if s.len() == 0 { return vec![] }
    s.split(spl).map(|s| s.to_string()).collect::<Vec<_>>()
}

fn main() {

    let line0 = read_line_split(" ");
    let n = line0[0].parse::<usize>().unwrap();
    let mut capit1 = line0[1].parse().unwrap();
    let mut capit2 = line0[2].parse().unwrap();

    let inp: Vec<usize> = read_line_split(" ").iter().map(|s| s.parse().unwrap()).collect::<Vec<_>>();

    //let n = 3;
    //let mut capit1 = 2;
    //let mut capit2 = 3;
    //let inp = vec![2,2];

    //let n = 6;
    //let mut capit1 = 2;
    //let mut capit2 = 4;
    //let inp = vec![6,1,2,4,2];

    capit1 -= 1;
    capit2 -= 1;
    let inp = inp.iter().map(|&vx| vx-1).collect::<Vec<_>>();

    let mut adj_li: Vec<Vec<i64>> = vec![];

    let mut vx_ = 0;
    for &vx in &inp {
        if vx_ == capit1 { vx_ += 1; }
        while vx_ >= adj_li.len() || vx >= adj_li.len() { adj_li.push(vec![]); }
        adj_li[vx].push(vx_ as i64);
        adj_li[vx_].push(vx as i64);

        //println!("{vx} {vx_}");

        vx_ += 1;
    }

    let mut map = vec![-1; inp.len()+1];
    create_map_dfs(&adj_li, &mut map, -1, capit2);
    //println!("{:?}", adj_li);

    let map = map.iter().filter(|&&vx| vx >= 0).collect::<Vec<_>>();
    let map = map.iter().map(|&&vx| (vx+1).to_string()).collect::<Vec<_>>();

    println!("{}", map.join(" "));
}

fn create_map_dfs(adj_li: &Vec<Vec<i64>>, map: &mut Vec<i64>, last_vx: i64, vx: i64) {
    for &vx_ in &adj_li[vx as usize] {
        if last_vx != vx_ {
            map[vx_ as usize] = vx;
            create_map_dfs(adj_li, map, vx, vx_);
        }
    }
}


// ---------- begin kth root ----------
// floor(a ^ (1 / k))
fn kth_root(a: u64, k: u64) -> u64 {
    assert!(k > 0);
    if a == 0 {
        return 0;
    }
    if k >= 64 {
        return 1;
    }
    if k == 1 {
        return a;
    }
    let valid = |x: u64| -> bool {
        let mut t = x;
        for _ in 1..k {
            let (val, ok) = t.overflowing_mul(x);
            if !(!ok && val <= a) {
                return false;
            }
            t = val;
        }
        true
    };
    let mut ok = 1;
    let mut ng = 2;
    while valid(ng) {
        ok = ng;
        ng *= 2;
    }
    while ng - ok > 1 {
        let mid = ok + (ng - ok) / 2;
        if valid(mid) {
            ok = mid;
        } else {
            ng = mid;
        }
    }
    ok
}
// ---------- end kth root ----------

use std::cmp::*;

type Map = std::collections::BTreeMap<u64, (u64, u64)>;

fn calc(n: u64, map: &mut Map) -> (u64, u64) {
    if n == 0 {
        return (0, 0);
    }
    if let Some(v) = map.get(&n) {
        return *v;
    }
    let p = kth_root(n, 3);
    let v = p.pow(3);
    let (a, b) = calc(v - 1, map);
    let (c, d) = calc(n - v, map);
    let (c, d) = (c + 1, d + v);
    let ans = max((a, b), (c, d));
    map.insert(n, ans);
    ans
}

fn run() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let m: u64 = s.trim().parse().unwrap();
    let mut memo = Map::new();
    let (cnt, x) = calc(m, &mut memo);
    println!("{} {}", cnt, x);
}

fn main() {
    run();
}


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// ここまで

fn run() {
    input! {
        n: usize,
        a: [usize; n],
    }
    let m = 5000;
    let mut weight = vec![0; m + 1];
    for a in a {
        if a == 0 {
            weight[1] += 1;
        } else {
            weight[a] += 1;
        }
    }
    let mut factor: Vec<usize> = vec![m; m + 1];
    let mut prime = vec![];
    for i in 2..=m {
        if factor[i] == m {
            for j in 1..=(m / i) {
                factor[j * i] = prime.len();
            }
            prime.push(i);
        }
    }
    let mut cnt = vec![vec![0; prime.len()]; m + 1];
    for i in 2..=m {
        let mut c = cnt[i - 1].clone();
        let mut t = i;
        while t > 1 {
            let k = factor[t];
            let p = prime[k];
            while t % p == 0 {
                c[k] += 1;
                t /= p;
            }
        }
        cnt[i] = c;
    }
    let cnt = cnt;
    let mut root_sum = 0u64;
    for i in 1..=m {
        root_sum += cnt[i].iter().fold(0, |s, a| s + *a) * weight[i];
    }
    let all = n as u64;
    let root_sum = root_sum;
    let mut dfs = vec![(2, m + 1, prime.len() - 1, 0, all - weight[1], root_sum)];
    let mut ans = root_sum;
    while let Some((l, r, index, num, sum, w)) = dfs.pop() {
        ans = std::cmp::min(ans, w);
        if l >= r || index >= prime.len() {
            continue;
        }
        assert!(num <= cnt[l][index]);
        if cnt[l][index] > num {
            dfs.push((l, r, index, num + 1, sum, w + all - 2 * sum));
        } else if cnt[l][index] == cnt[r - 1][index] {
            dfs.push((l, r, index - 1, 0, sum, w));
        } else {
            let mut zero = 0;
            let mut k = l;
            while k < r && cnt[k][index] == cnt[l][index] {
                zero += weight[k];
                k += 1;
            }
            dfs.push((l, k, index - 1, 0, zero, w));
            dfs.push((k, r, index, num, sum - zero, w));
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}


#![allow(non_snake_case)]
#[allow(dead_code)] fn read_line() -> String { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).expect("failed to read line"); buffer.trim().to_string() }
#[allow(dead_code)] fn read<T : std::str::FromStr>() -> T where T::Err: std::fmt::Debug { read_line().trim().parse::<T>().expect("failed to read value") }
#[allow(dead_code)]fn read_vec<T : std::str::FromStr>() -> Vec<T> where T::Err: std::fmt::Debug { read_line().split_whitespace().map(|x| x.parse::<T>().expect("failed to read values")).collect() }
#[allow(dead_code)] fn lock_stdout() -> std::io::BufWriter<std::io::StdoutLock<'static>> { let stdout = std::io::stdout().lock(); std::io::BufWriter::new(stdout) }
#[allow(dead_code)] struct StdoutLogger {buf: std::io::BufWriter<std::io::StdoutLock<'static>>}impl StdoutLogger {fn log(&mut self, s: &str) {std::io::Write::write(&mut self.buf, s.as_bytes()).expect("error writing stdout");std::io::Write::write(&mut self.buf, "\n".as_bytes()).expect("error writing stdout");}}
#[allow(dead_code)] macro_rules! init {($name: ident) => {#[allow(unused_mut)]let mut $name = StdoutLogger{buf:lock_stdout()};}}

fn main() {
    init!(outp);

    let n = read::<usize>();
    let inp = read_line();

    // let n = 4;
    // let inp = "ab. b. de.";

    // let n = 146;
    // let inp = "iIQVkDsPqzAJyBrtHk EhBSN gzDoigItCMzETerb cIbXhTPbKYMdMoYqyFTEN. qcrrseVwmaZEiQUQoGT SUyErST lJDejKkjqTdoUrHR tsZYDyI? pmuNNHYqQUISxdZfWOB XdEECvNz hnNmVfODaIC qjhRIEPAlEsQBxo apZ! gCpqoiUFIwWLBOmYubywj qJojFVhLd dCpovICpXHfgihydEOoij?";

    // let n = 2;
    // let inp = "How are you?";

    // let n = 19;
    // let inp = "Hello! Do you like fish? Why?";

    let sntncs = inp.split(['.', '?', '!']);
    let mut cnt = 1;
    let mut sntnc_c = 0;
    let mut p = 0;
    let mut i = 0;
    for sntnc in sntncs {
        if sntnc.len()==0 {continue};
        let sntnc = sntnc.trim();

        let sntnc_len = sntnc.len()+1; //+1 for .,?,!
        let spaced_sntnc_len = sntnc_len + if i==0{0}else{1};
        if sntnc_len > n {
            println!("Impossible");
            return;
        }

        //println!("sntnc:{sntnc} len:{}", sntnc.len());
        if p+spaced_sntnc_len<=n {
            // println!("spaced_sntnc_len {}", spaced_sntnc_len);
            sntnc_c += 1;
            p += spaced_sntnc_len;
        } else {
            if sntnc_c==0 {
                println!("Impossible");
                return;
            }
            p = sntnc_len;
            cnt += 1;
        }

        i+=1;
    }
    println!("{cnt}");

}

[{'input': ['25\r\nHello. I am a little walrus.\r\n'], 'output': ['2\r\n']}, {'input': ['2\r\nHow are you?\r\n'], 'output': ['Impossible\r\n']}, {'input': ['19\r\nHello! Do you like fish? Why?\r\n'], 'output': ['3\r\n']}, {'input': ['4\r\na. A.\r\n'], 'output': ['2\r\n']}, {'input': ['191\r\nEvx vnxZtUSgtzH yDNXCsTaxCKQus gVZLHppOplkGGekIK xbme. krbusMqUs YEnBBTJpjNicZPlx TqEtBPcbejZMzvn fFTub CHYWLmiOFkDdzR! LoQmXPfHJ KVnfrbrFooVSkj xwAZwrRr DdILZ kpco cLoRmJbVKhnbOEhnHKpci. PgYhxFPXdlvlrp mDLZBnVRf AgRMUjxepFuLyKlIAhLS wtmEiLDNUAHpZEsKnkOu!\r\n'], 'output': ['2\r\n']}, {'input': ['146\r\niIQVkDsPqzAJyBrtHk EhBSN gzDoigItCMzETerb cIbXhTPbKYMdMoYqyFTEN. qcrrseVwmaZEiQUQoGT SUyErST lJDejKkjqTdoUrHR tsZYDyI? pmuNNHYqQUISxdZfWOB XdEECvNz hnNmVfODaIC qjhRIEPAlEsQBxo apZ! gCpqoiUFIwWLBOmYubywj qJojFVhLd dCpovICpXHfgihydEOoij?\r\n'], 'output': ['2\r\n']}, {'input': ['151\r\nayDIuxJXWNqu OImqJLodviANkQNxZ OpDpwyoPQdZyosXJpqRx! ZFQNQJPnoEVUEEbjqs iyfUYK HuGCOtlsEllsCiHIdEuW ZmlRSWVOmLAD MSYsC? CGKxobjmddejDDdF qbQsAWi qxViwV iLmPHfhLjP ZfNCItjZikwaQyhQGC? bvSaaZhwHdbNKSiiI bEJXRjANEasfrElNHPA UuQCajtuODHgxwgL qbssJss TqT.\r\n'], 'output': ['2\r\n']}, {'input': ['123\r\nOjg CVJm qfE RnHislFds nNKKt TCPLWukqNGAsVBplYbTfq? VeYKjfFGTzXWA ydpVZLIImNub yApKnAHv iXQmqv GjQvxrnAgtfTApiQyCKtg. GdmapGwvI udRqxTbnzgnOUNZx slAuEuLGCJycZJvtCczQ vommS xuuT eIK! DOJeFEaubbz HYLGlIIlNKfyaJQKVN eFNnUvKKCQLXvGhwX gjmRscMkedELUlHq? aTbyMGB EofzX wcAEjyRQpxghWvXhdJb cwIz FEUsEFicYZ.\r\n'], 'output': ['3\r\n']}, {'input': ['126\r\ntjQvloOnRednqfvIRudX wAPhGdwEZ BiuuuAW EfSzDuRTdC rptjpHnxyM? FkLaTBruN IwuIQMdpdUpn etTVVJUsKztaR YNY EAENiDgJwYXDDrayjyuKp! yKqRNHznLRpnTqjisR LuapWDnWmwYDE NcClOZBNzMYrpa? SEZdSZIgBekpCPvyEiO AMjztArkFRJuS ilycvolFExqxrXJK. sLvBUxjIOomxUqYd jZsOXWN iBtqSykbeUbAsQgRVs DinPLrpzt.\r\n'], 'output': ['3\r\n']}, {'input': ['118\r\ngweVo bjbEKaZQw PpSi AWOYt sQSvAHNRswh vUaGuLbtExNECz! USsQxMCjaGOmUESwHvyY SshkERibaWkmNLSZOtWZy FFTUWQgekPRjLRetAdSFt! sIhcimZTisFvndrYioLF HetLn wjoaDUKfbkagupl QdYb fFiV GNqBygStKQw. XLiYZEOGnTLSHmCwktEr pVBePMoRGopNt LdEujxuxzmlbycQdR?\r\n'], 'output': ['4\r\n']}, {'input': ['16\r\nAbacaba. Abacaba. abacaba. abacab.\r\n'], 'output': ['3\r\n']}, {'input': ['21\r\nHello. I am a little walrus.\r\n'], 'output': ['2\r\n']}, {'input': ['16\r\nAbacaba. Abacab. abacaba. abacaba.\r\n'], 'output': ['3\r\n']}, {'input': ['10\r\nhello! how are you?\r\n'], 'output': ['Impossible\r\n']}, {'input': ['5\r\nabc. abcd.\r\n'], 'output': ['2\r\n']}, {'input': ['16\r\nabacaba. abacab. Abacaba. Abacaba.\r\n'], 'output': ['3\r\n']}, {'input': ['5\r\na. b. c. d.\r\n'], 'output': ['2\r\n']}, {'input': ['8\r\nabc! ab.\r\n'], 'output': ['1\r\n']}, {'input': ['2\r\na. b.\r\n'], 'output': ['2\r\n']}]


// ---------- begin input macro ----------
// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
// ---------- end input macro ----------

fn run() {
    input! {
        m: u64,
        xaniar: (usize, usize, u64, u64),
        abol: (usize, usize, u64, u64),
    }
    let cond = |b: bool| {
        if !b {
            println!("-1");
            std::process::exit(0);
        }
    };
    let next = |h: usize| -> usize {
        let x = xaniar.2;
        let y = xaniar.3;
        ((h as u64 * x + y) % m) as usize
    };
    let mut time = vec![None; m as usize];
    let mut p = xaniar.0;
    time[p] = Some(0);
    let mut k = 1;
    p = next(p);
    while time[p].is_none() {
        time[p] = Some(k);
        k += 1;
        p = next(p);
    }
    let step = k - time[p].unwrap();
    let a = xaniar.1;
    cond(time[a].is_some());
    if time[a].unwrap() < time[p].unwrap() {
        let next = |h: usize| -> usize {
            let x = abol.2;
            let y = abol.3;
            ((h as u64 * x + y) % m) as usize
        };
        let t = time[a].unwrap();
        let mut p = abol.0;
        for _ in 0..t {
            p = next(p);
        }
        cond(p == abol.1);
        println!("{}", t);
        return;
    }
    let t = time[a].unwrap();
    let mut abol = abol;
    for _ in 0..t {
        abol.0 = {
            let x = abol.2;
            let y = abol.3;
            ((abol.0 as u64 * x + y) % m) as usize
        };
    }
    let mut mat = (1, 0);
    for _ in 0..step {
        mat = (mat.0 * abol.2 % m, (mat.1 * abol.2 + abol.3) % m);
    }
    abol.2 = mat.0;
    abol.3 = mat.1;
    let mut time = vec![None; m as usize];
    let next = |h: usize| -> usize {
        let x = abol.2;
        let y = abol.3;
        ((h as u64 * x + y) % m) as usize
    };
    let mut p = abol.0;
    time[abol.0] = Some(0);
    p = next(p);
    let mut k = 1;
    while time[p].is_none() {
        time[p] = Some(k);
        p = next(p);
        k += 1;
    }
    cond(time[abol.1].is_some());
    let ans = time[abol.1].unwrap() as u64 * step as u64 + t as u64;
    println!("{}", ans);
}

fn main() {
    run();
}


fn main() {

    use std::io::{self, Read};
    use std::cmp::Ordering;
    use std::collections::{HashMap,HashSet};
    use std::mem;

    let mut buffer = String::new();
    let stdin = io::stdin();
    let mut handle = stdin.lock();

    handle.read_to_string(&mut buffer).unwrap();

    let input_strs = buffer.split_whitespace().take(3).map( |x| x.parse::<i64>().unwrap() ).collect::< Vec<i64> >();

    let n = *input_strs.iter().nth(0).unwrap();

    let mut hs = HashSet::new();
    hs.insert(0);

    let mut dp_count = HashMap::new();

    //dp_count.insert( &0, 1 );

    //strategy: use dp and the number of additional unique values added per round tops off at some point for value denominations of 1, 5, 10, 50
    // so use that value for bigger number of rounds
    for i in 0..13 {
        let mut temp = HashSet::new();
        for j in hs.iter() {
            temp.insert( *j + 1i64 );
            temp.insert( *j + 5i64 );
            temp.insert( *j + 10i64 );
            temp.insert( *j + 50i64 );
        }
        mem::swap( & mut temp, & mut hs );
        let count = hs.len();
        dp_count.insert(i+1, count);
    }

    let ans = if n <= 12 {
        *dp_count.get(&n).expect("dp_count") as i64
    } else {
        let increment = *dp_count.get(&12).unwrap() - *dp_count.get(&11).unwrap();
        *dp_count.get(&12).unwrap() as i64 + (n as i64 - 12i64) * increment as i64
    };
    println!( "{}", ans );
}