#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(overflowing_literals)]
#![allow(unused_must_use)]

use std::collections::*;
use std::io::*;
use std::cmp::{min, max};
use std::f64::consts::*;
use std::mem::swap;
use std::fs::File;
use std::rc::*;
use std::ascii::*;
use std::ops::*;

const INF: i32 = std::i32::MAX;
const LINF: i64 = std::i64::MAX;
const MOD: i32 = 1000000007;

#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone)]
struct Pair<A: Eq + Ord + Clone, B: Eq + Ord + Clone>(A, B);

struct Input<Buf: BufRead>
{
	buffer: Buf
}

impl<Buf: BufRead> Input<Buf>
{
	fn read_line(&mut self) -> String {
		let mut v = Vec::new();
		let mut x = [255u8];
		self.buffer.read(&mut x).expect("EOF");
		while x[0] < b' ' && x[0] != 255u8 {
			x[0] = 255u8;
			self.buffer.read(&mut x).expect("EOF");
		}
		while x[0] >= b' ' && x[0] != 255u8 {
			v.push(x[0]);
			x[0] = 255u8;
			self.buffer.read(&mut x).expect("EOF");
		}
		String::from_utf8(v).unwrap()
	}

	fn read_word(&mut self) -> String {
		let mut v = Vec::new();
		let mut x = [255u8];
		self.buffer.read(&mut x).expect("EOF");
		while x[0] <= b' ' && x[0] != 255u8 {
			x[0] = 255u8;
			self.buffer.read(&mut x).expect("EOF");
		}
		while x[0] > b' ' && x[0] != 255u8 {
			v.push(x[0]);
			x[0] = 255u8;
			self.buffer.read(&mut x).expect("EOF");
		}
		String::from_utf8(v).unwrap()
	}
	#[inline]
	fn read_int(&mut self) -> i32 {
		self.read_word().parse::<i32>().expect("Parsing error")
	}
	#[inline]
	fn read_long(&mut self) -> i64 {
		self.read_word().parse::<i64>().expect("Parsing error")
	}
	#[inline]
	fn read_usize(&mut self) -> usize {
		self.read_word().parse::<usize>().expect("Parsing error")
	}
	#[inline]
	fn read_double(&mut self) -> f64 {
		self.read_word().parse::<f64>().expect("Parsing error")
	}
}
macro_rules! read {
    () => {};
	($inf:ident,$($t:ty),*) => ({($({$inf.read_word().parse::<$t>().expect("Parsing error")}),*)});
}
fn gcd<T: RemAssign + Ord + From<i32> + Copy>(x: T, y: T) -> T {
	let (mut a, mut b) = (x, y);
	while b > T::from(0) {
		a %= b;
		swap(&mut a, &mut b);
	}
	a
}

fn main() {
	match std::env::var("home") {
		Ok(_x) => {
			let mut inf = Input {
				buffer: BufReader::new(File::open("input.txt").expect("File not found"))
			};
			let mut ouf = BufWriter::new(stdout());
			solve(&mut inf, &mut ouf);
		}
		Err(_e) => {
			let mut inf = Input { buffer: BufReader::new(stdin()) };
			let mut ouf = BufWriter::new(stdout());
			solve(&mut inf, &mut ouf);
		}
	}
}

fn solve<Inner: BufRead, Output: Write>(inf: &mut Input<Inner>, ouf: &mut Output)
{
	let k = read!(inf,usize);
	let mut v = vec![0; k];
	for i in 0..k {
		v[i] = read!(inf,i32);
	}
	v.sort();
	writeln!(ouf, "{}", max(v[k - 1] - 25, 0));
}


#[allow(unused_imports)]
use std::io::{stdin, Read, StdinLock};
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::str::FromStr;
#[allow(unused_imports)]
use std::collections::{HashSet, HashMap, BinaryHeap};
#[allow(unused_imports)]
use std::vec::Vec;

#[allow(dead_code)]
const INF: i32 = 1000_000_000;
#[allow(dead_code)]
const INFLL: i64 = 1000_000_000_000_000_000;
#[allow(dead_code)]
const EPS: f64 = 1.0e-10;
#[allow(dead_code)]
const MOD: i32 = 1000_000_007;

struct Scanner<'a> {
    cin: StdinLock<'a>,
}

impl<'a> Scanner<'a> {
    #[allow(dead_code)]
    fn new(cin: StdinLock<'a>) -> Scanner<'a> {
        Scanner {cin: cin}
    }

    #[allow(dead_code)]
    fn read1<T: FromStr>(&mut self) -> Option<T> {
        let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)
                    .skip_while(|c| c.is_whitespace())
                    .take_while(|c| !c.is_whitespace())
                    .collect::<String>();
        token.parse::<T>().ok()
    }

    #[allow(dead_code)]
    fn read<T: FromStr>(&mut self) -> T {
        self.read1().unwrap()
    }
}

fn main() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin);

    let a: i32 = sc.read();
    let x: i32 = sc.read();
    let y: i32 = sc.read();
    let x = 2 * x;
    let y = 2 * y;
    let a = 2 * a;
    let mut ans = -1;
    if y % a != 0 {
        if 0 < y && y < a {
            if -a / 2 < x && x < a / 2 {
                ans = 1;
            }
        } else {
            let j = (y - a) / a;
            if j % 2 == 0 {
                if -a / 2 < x && x < a / 2 {
                    ans = 3 * j / 2 + 2;
                }
            } else {
                if -a < x && x < 0 {
                    ans = 3 * (j + 1) / 2;
                } else if 0 < x && x < a {
                    ans = 3 * (j + 1) / 2 + 1;
                }
            }
        }
    }

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


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

fn not_all_zero(vec: &[u32]) -> bool {
    vec.iter().any(|n| *n != 0)
}

fn take_row(vec: &mut [u32]) -> u32 {
    let mut n = 0;

    for (i, item) in vec.iter_mut().enumerate() {
        if *item > 0 {
            n += 10_u32.pow(i as u32);
            *item -= 1;
        }
    }

    n
}

fn main() {
    let mut n: u32 = read();
    let mut digits = Vec::new();

    while n > 0 {
        digits.push(n % 10);
        n /= 10;
    }

    let mut nums = Vec::new();

    while not_all_zero(&digits) {
        nums.push(take_row(&mut digits));
    }

    println!("{}", nums.len());
    println!("{}",
        nums
            .iter()
            .map(|n| n.to_string())
            .collect::<Vec<_>>()
            .join(" ")
    );
}

fn read_line() -> String {
    let mut pre_n = String::new();
    io::stdin().read_line(&mut pre_n).unwrap();
    pre_n
}

fn read<T: FromStr>() -> T
    where <T as FromStr>::Err: fmt::Debug
{
    read_line().trim().parse().unwrap()
}


fn hash(a: &[u64], cnt: &[u64]) -> u64 {
    let mut hash = 0;
    for i in 0..10 {
        hash = (cnt[i] + 1) * hash + a[i];
    }
    hash
}

fn decode(mut hash: u64, cnt: &[u64]) -> Vec<u64> {
    let mut d = vec![];
    for i in (0..10).rev() {
        d.push(hash % (cnt[i] + 1));
        hash /= cnt[i] + 1;
    }
    d.reverse();
    d
}

fn run() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let mut it = s.trim().split_whitespace();
    let mut n: u64 = it.next().unwrap().parse().unwrap();
    let m: usize = it.next().unwrap().parse().unwrap();
    let mut cnt = vec![0; 10];
    let mut len = 0;
    while n > 0 {
        let k = (n % 10) as usize;
        cnt[k] += 1;
        len += 1;
        n /= 10;
    }
    let mut now = std::collections::BTreeMap::new();
    now.insert((hash(&cnt, &cnt), 0), 1u64);
    for p in 0..len {
        let mut next = std::collections::BTreeMap::new();
        for (k, v) in now.iter() {
            let (h, rem) = *k;
            let a = decode(h, &cnt);
            for d in 0..10 {
                if a[d] > 0 && !(p == 0 && d == 0) {
                    let mut b = a.clone();
                    b[d] -= 1;
                    let r = (10 * rem + d) % m;
                    *next.entry((hash(&b, &cnt), r)).or_insert(0u64) += *v;
                }
            }
        }
        now = next;
    }
    let mut ans = 0;
    for (k, v) in now.iter() {
        if k.1 == 0 {
            ans += *v;
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}


struct Scan {
    buffer: std::collections::VecDeque<String>
}

impl Scan {
    fn new() -> Scan {
        Scan { buffer: std::collections::VecDeque::new() }
    }

    fn next<T: std::str::FromStr>(&mut self)-> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

}

fn dfs_moves(acc: usize, current: usize, goal: usize, dist: &mut [usize;20000]) {
    if dist[current]<=acc { return; }
    dist[current] = acc;
    if current >= goal {
        dist[goal] = dist[goal].min(acc+current-goal);
        return;
    }
    dfs_moves(acc + 1, current*2, goal, dist);
    if current > 1 {
        dfs_moves(acc + 1, current-1, goal, dist);
    }
}

fn _main() {
    let mut scan = Scan::new();
    let n: usize = scan.next();
    let m: usize = scan.next();
    if m<= n {
        println!("{}", n - m);
        return;
    }
    let mut dist = [std::usize::MAX; 20000];
    dfs_moves(0, n, m, &mut dist);
    println!("{}", dist[m]);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();
}


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, [ $t:tt ]) => {{
        let len = read_value!($next, usize);
        (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    }};

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn calc(g: &[Vec<usize>], revg: &[Vec<usize>], cnt: &mut [usize]) {
    let n = revg.len();
    let mut outdeg = vec![0; n];
    let mut zeroback = vec![0; n]; // zeroback[v] = #{w | (v -> u) in g, deg[v] = 1}
    let mut zero = 0;
    let mut zs = BTreeSet::new();
    for v in 0..n {
        for &w in &revg[v] {
            if outdeg[w] == 0 {
                zero -= 1;
                zs.remove(&w);
                zeroback[v] += 1;
            }
            if outdeg[w] == 1 {
                for &k in &g[w] {
                    if k < v {
                        zeroback[k] -= 1;
                    }
                }
            }
            outdeg[w] += 1;
        }
        cnt[v] += zero;
        if zero == 1 {
            let &x = zs.iter().next().unwrap();
            cnt[v] += zeroback[x];
        }
        zero += 1;
        zs.insert(v);
    }
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (write!(out,$($format)*).unwrap());
    }
    input! {
        n: usize,
        uv: [(usize1, usize1)],
    }
    let mut g = vec![vec![]; n];
    let mut revg = vec![vec![]; n];
    for &(u, v) in &uv {
        g[u].push(v);
        revg[v].push(u);
    }
    // find a topological order
    let mut ord = vec![];
    {
        let mut indeg = vec![0; n];
        let mut que = VecDeque::new();
        for i in 0..n {
            indeg[i] = revg[i].len();
            if revg[i].is_empty() {
                que.push_back(i);
            }
        }
        while let Some(v) = que.pop_front() {
            ord.push(v);
            for &w in &g[v] {
                indeg[w] -= 1;
                if indeg[w] == 0 {
                    que.push_front(w);
                }
            }
        }
    }
    assert_eq!(ord.len(), n);
    // Replace g and revg
    {
        let mut invord = vec![0; n];
        for i in 0..n {
            invord[ord[i]] = i;
        }
        for i in 0..n {
            g[i].clear();
            revg[i].clear();
        }
        for &(u, v) in &uv {
            let a = invord[u];
            let b = invord[v];
            g[a].push(b);
            revg[b].push(a);
        }
    }
    let mut cnt = vec![0; n];
    calc(&g, &revg, &mut cnt);
    cnt.reverse();
    for i in 0..n {
        for w in g[i].iter_mut() {
            *w = n - 1 - *w;
        }
        for w in revg[i].iter_mut() {
            *w = n - 1 - *w;
        }
    }
    g.reverse();
    revg.reverse();
    calc(&revg, &g, &mut cnt);
    cnt.reverse();
    let mut ans = 0;
    for i in 0..n {
        if cnt[i] <= 1 {
            ans += 1;
        }
    }
    puts!("{}\n", ans);
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}


use std::io;
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![],
        }
    }

    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 gcd(a: i64, b: i64) -> i64 {
    if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}

fn to_fraction(num: i64, denom: i64) -> (i64, i64) {
    let g = gcd(num, denom);
    (num / g, denom / g)
}

fn max_fraction(num1: i64, denom1: i64, num2: i64, denom2: i64) -> (i64, i64) {
    if num1 * denom2 < num2 * denom1 {
        to_fraction(num2, denom2)
    }
    else {
        to_fraction(num1, denom1)
    }
}

fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) {
    let a: i64 = scan.token();
    let b: i64 = scan.token();
    let c: i64 = scan.token();
    let d: i64 = scan.token();

    let num1 = a * d - b * c;
    let denom1 = a * d;
    let num2 = b * c - a * d;
    let denom2 = b * c;

    let ans = max_fraction(num1, denom1, num2, denom2);
    writeln!(out, "{}/{}", ans.0, ans.1).ok();
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());
    solve(&mut scan, &mut out);
}


// {{{ by shik

use std::io;

#[allow(dead_code)]
fn gets() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

#[allow(unused_macros)]
macro_rules! R {
    ( $ty:ty, ... ) => {
        gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::<Vec<_>>()
    };
    ( $($ty:ty),* ) => {{
        let line = gets();
        let mut it = line.split_whitespace();
        ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )
    }}
}

#[allow(unused_macros)]
macro_rules! W {
    ( $x:expr ) => {{
        println!("{}", $x);
    }};
    ( $x:expr, $($xs:expr),* ) => {{
        print!("{} ", $x);
        W!($($xs),*);
    }}
}

#[allow(unused_macros)]
macro_rules! join {
    ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }
}

#[allow(unused_macros)]
macro_rules! dump {
    ($($x:expr),*) => {
        eprintln!(join!($(concat!(stringify!($x), " = {:?}")),*; ", "), $($x),*);
    }
}

// }}}

fn main() {
    let (n, m) = R!(usize, usize);
    let mut cur: usize = n;
    for day in 1.. {
        cur -= 1;
        if day % m == 0 {
            cur += 1;
        }
        if cur == 0 {
            println!("{}", day);
            break;
        }
    }
}


#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_labels)]

use std::char::*;
use std::cmp::*;
use std::collections::*;
use std::io::*;
use std::str::FromStr;

macro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);}}
macro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
macro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
macro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

use std::f64;

fn min<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { a }
    else { b }
}

fn max<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { b }
    else { a }
}

const MAX:usize = 30;
const INF:i64 = std::i64::MAX;
const MOD:i64 = 1e9 as i64 + 7;

struct Graph {
    e: Vec<Vec<usize>>,
    v: Vec<usize>,
    u: Vec<usize>,
    f: Vec<bool>,
    c: i64,
    vc: Vec<i64>,
}

impl Graph {
    fn new(n:usize) -> Self {
        Graph {
            e: vec![vec![];n],
            v: vec![],
            u: vec![n;n],
            f: vec![false;n],
            c: 0,
            vc: vec![0;n],
        }
    }

    fn dfs(&mut self, crt: usize) {
        if self.f[crt] { return; }
        self.c += 1;
        self.f[crt] = true;
        self.v.push(crt);
        self.vc[crt] = self.c;
        self.u[crt] = self.v.len()-1;
        for i in 0..self.e[crt].len() {
            self.dfs(self.e[crt][i]);
        }
        //debug!(crt, self.c, self.vc[crt]);
        self.vc[crt] = self.c - self.vc[crt];
    }
}

fn main() {
    //let t:usize = read();

    //'outer: for _ in 0..t {
        let n:usize = read();
        let k:i64 = read();
        let a:Vec<i64> = (0..n).map(|_| read()).collect();

        let mut idx = 0;
        for i in 0..n {
            if a[i] > k { break; }
            idx = i+1;
        }
        let mut idx2 = n;
        for i in (0..n).rev() {
            if a[i] > k { break; }
            idx2 = i;
        }
        if idx == n {
            println!("{}", n);
        } else {
            println!("{}", idx+(n-idx2));
        }
    //}
}

/*

*/


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::Read;

#[allow(dead_code)]
fn getline() -> String {
    let mut ret = String::new();
    std::io::stdin().read_line(&mut ret).ok().unwrap();
    ret
}

fn get_word() -> String {
    let stdin = std::io::stdin();
    let mut stdin=stdin.lock();
    let mut u8b: [u8; 1] = [0];
    loop {
        let mut buf: Vec<u8> = Vec::with_capacity(16);
        loop {
            let res = stdin.read(&mut u8b);
            if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {
                break;
            } else {
                buf.push(u8b[0]);
            }
        }
        if buf.len() >= 1 {
            let ret = String::from_utf8(buf).unwrap();
            return ret;
        }
    }
}

#[allow(dead_code)]
fn get<T: std::str::FromStr>() -> T { get_word().parse().ok().unwrap() }

fn main() {
    let s: Vec<char> = get_word().chars().collect();
    let mut ans = 0;
    for i in 0..4_000_000 {
        let t: Vec<_> = format!("{}", 25 * i).chars().collect();
        if s.len() == t.len() {
            let mut x = 0;
            let mut ok = true;
            for i in 0..s.len() {
                if s[i] != t[i] && s[i] != '_' && s[i] != 'X' {
                    ok = false;
                    break;
                }
                if s[i] == 'X' {
                    let idx = t[i] as u8 - b'0';
                    x |= 1 << idx;
                }
            }
            if ok && (x & -x) == x {
                ans += 1;
            }
        }
    }
    println!("{}", ans);
}


//spnauti-rust
use std::io::*;
use std::str::*;
use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::*;
#[allow(unused_imports)] use std::collections::*;

#[allow(unused_macros)]
macro_rules! a {
    ($c: tt, $x: expr, $y: expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
struct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).ok();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn u(&mut self) ->  usize { self.p()                }
    fn vi(&mut self, n: usize) -> Vec<i32> {
        self.vp::<i32>(n)
    }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}

#[allow(dead_code)]
fn build_counting_hashmap<K: Eq + std::hash::Hash, T>(i: T) -> HashMap<K,usize>
    where T: Iterator<Item = K> {
    let mut m = HashMap::new();
    for k in i {
        let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };
        m.insert(k, n);
    }
    m
}

fn main() {
    let mut bin = String::new();
    let mut input = WordReader::from_stdin(&mut bin);
    let mut bout = BufWriter::new(stdout());

    let n = input.u();
    let m = input.i();
    let mut c = vec![0; 101];
    let mut sum = 0;
    for _ in 0..n {
        let t = input.i();
        sum += t;
        let mut s = sum - m;
        let mut res = 0;
        if s > 0 {
            for i in (1..101).rev() {
                let x = c[i as usize];
                if x * i <= s {
                    s -= x * i;
                    res += x;
                } else {
                    res += (s + i - 1) / i;
                    break;
                }
            }
        }
        c[t as usize] += 1;
        write!(bout, "{} ", res).ok();
    }
}


use std::io;
use std::io::Read;

fn main() {
    let mut text = String::new();
    io::stdin().read_to_string(&mut text).unwrap();
    let mut iter = text.split_whitespace();//.map(|x| x.parse::<i64>().unwrap());
    let n = iter.next().unwrap().parse::<i64>().unwrap();
    let s = iter.next().unwrap();
    let mut up = true;
    let mut down = true;
    let mut left = true;
    let mut right = true;
    for c in s.chars() {
        let d = c as i64 - '0' as i64;
        if d == 1 || d == 2 || d == 3 {
            up = false;
        }
        if d == 7 || d == 9 || d == 0 {
            down = false;
        }
        if d == 1 || d == 4 || d == 7 || d == 0 {
            left = false;
        }
        if d == 3 || d == 6 || d == 9 || d == 0 {
            right = false;
        }
    }
    println!("{}", if (up || down || left || right) {"NO"} else {"YES"});

}

fn get_pos(num: i64) -> (i64, i64) {
    if num == 0 {
        (3, 1)
    } else {
        ((num - 1) / 3, (num - 1) % 3)
    }
}


use std::io;

const M: u64 = 1_000_000_007;

fn mult((a, b): (u64, u64), (c, d): (u64, u64)) -> (u64, u64) {
    ((a*c) % M, (a*d + b) % M)
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let input = input.split_whitespace().map(|s| s.parse().unwrap()).collect::<Vec<u64>>();
    let a = input[0];
    let b = input[1];
    let mut n = input[2];
    let x = input[3];

    let mut g = (1, 0);
    let mut f = (a, b);

    while n != 0 {
        if n % 2 == 1 {
            g = mult(g, f);
        }
        f = mult(f, f);
        n = n / 2;
    }

    let (a, b) = g;
    println!("{}", (a*x + b) % M);
}


use std::io;

fn main() {
    let mut val = String::new();

    io::stdin().read_line(&mut val)
        .expect("Не удалось прочитать строку");

    let val: i32 = val.trim().parse()
        .expect("Пожалуйста, введите число!");

    let ans = val / 5;
    println!("{}", ans + (val % 5 > 0) as i32);
}


use std::io;

fn main() {
  let mut ni = String::new();
  io::stdin().read_line(&mut ni).unwrap();
  let mut si = String::new();
  io::stdin().read_line(&mut si).unwrap();
  let sf = si.trim().matches("SF").collect::<Vec<&str>>().len();
  let fs = si.trim().matches("FS").collect::<Vec<&str>>().len();
  if sf > fs {
    println!("YES")
  } else {
    println!("NO")
  }
}


use std::io;

#[allow(dead_code)]
fn main() {
    let mut input = "".split_ascii_whitespace();
    let mut read = || loop {
        if let Some(word) = input.next() {
            break word;
        }
        input = {
            let mut input = "".to_owned();
            io::stdin().read_line(&mut input).unwrap();
            if input.is_empty() {
                panic!("reached EOF");
            }
            Box::leak(input.into_boxed_str()).split_ascii_whitespace()
        };
    };
    macro_rules! read(($ty:ty) => (read().parse::<$ty>().unwrap()));

    let n = read!(usize);
    let m = read!(usize);
    let mut sa = vec!["".to_string(); 0];
    for _ in 0..n {
        sa.push(read!(String));
    }
    let mut ca = vec![vec![' '; 0]; n];
    for i in 0..n {
        ca[i] = sa[i].chars().collect::<Vec<char>>();
    }
    let mut ba = vec![vec![false; m]; n];

    for i in 0..n {
        for j in 0..m {
            if ca[i][j] != 'P' {
                continue;
            }
            if i > 0 && ca[i - 1][j] == 'W' {
                ba[i - 1][j] = true;
            }
            if i < n - 1 && ca[i + 1][j] == 'W' {
                ba[i + 1][j] = true;
            }
            if j > 0 && ca[i][j - 1] == 'W' {
                ba[i][j - 1] = true;
            }
            if j < m - 1 && ca[i][j + 1] == 'W' {
                ba[i][j + 1] = true;
            }
        }
    }

    let mut r = 0;
    for i in 0..n {
        for j in 0..m {
            if ba[i][j] {
                r += 1;
            }
        }
    }

    println!("{}", r);
}


// ---------- begin ModInt ----------
const MOD: u32 = 998_244_353;

#[derive(Clone, Copy)]
struct ModInt(u32);

impl std::ops::Add for ModInt {
    type Output = ModInt;
    fn add(self, rhs: ModInt) -> Self::Output {
        let mut d = self.0 + rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::AddAssign for ModInt {
    fn add_assign(&mut self, rhs: ModInt) {
        *self = *self + rhs;
    }
}

impl std::ops::Sub for ModInt {
    type Output = ModInt;
    fn sub(self, rhs: ModInt) -> Self::Output {
        let mut d = self.0 + MOD - rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::SubAssign for ModInt {
    fn sub_assign(&mut self, rhs: ModInt) {
        *self = *self - rhs;
    }
}

impl std::ops::Mul for ModInt {
    type Output = ModInt;
    fn mul(self, rhs: ModInt) -> Self::Output {
        ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)
    }
}

impl std::ops::MulAssign for ModInt {
    fn mul_assign(&mut self, rhs: ModInt) {
        *self = *self * rhs;
    }
}

impl std::ops::Neg for ModInt {
    type Output = ModInt;
    fn neg(self) -> Self::Output {
        ModInt(if self.0 == 0 {0} else {MOD - self.0})
    }
}

impl std::fmt::Display for ModInt {
    fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::str::FromStr for ModInt {
    type Err = std::num::ParseIntError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let val = s.parse::<u32>()?;
        Ok(ModInt::new(val))
    }
}

#[allow(dead_code)]
impl ModInt {
    pub fn new(n: u32) -> ModInt {
        ModInt(n % MOD)
    }
    pub fn zero() -> ModInt {
        ModInt(0)
    }
    pub fn one() -> ModInt {
        ModInt(1)
    }
    pub fn pow(self, mut n: u32) -> ModInt {
        let mut t = ModInt::one();
        let mut s = self;
        while n > 0 {
            if n & 1 == 1 {
                t *= s;
            }
            s *= s;
            n >>= 1;
        }
        t
    }
    pub fn inv(self) -> ModInt {
        assert!(self.0 > 0);
        self.pow(MOD - 2)
    }
}
// ---------- end ModInt ----------
// ---------- begin Precalc ----------
#[allow(dead_code)]
struct Precalc {
    inv: Vec<ModInt>,
    fact: Vec<ModInt>,
    ifact: Vec<ModInt>,
}

#[allow(dead_code)]
impl Precalc {
    pub fn new(n: usize) -> Precalc {
        let mut inv = vec![ModInt::one(); n + 1];
        let mut fact = vec![ModInt::one(); n + 1];
        let mut ifact = vec![ModInt::one(); n + 1];
        for i in 2..(n + 1) {
            inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);
            fact[i] = fact[i - 1] * ModInt(i as u32);
            ifact[i] = ifact[i - 1] * inv[i];
        }
        Precalc {
            inv: inv,
            fact: fact,
            ifact: ifact,
        }
    }
    pub fn inv(&self, n: usize) -> ModInt {
        self.inv[n]
    }
    pub fn fact(&self, n: usize) -> ModInt {
        self.fact[n]
    }
    pub fn ifact(&self, n: usize) -> ModInt {
        self.ifact[n]
    }
    pub fn comb(&self, n: usize, k: usize) -> ModInt {
        if k > n {
            return ModInt::zero();
        }
        self.fact[n] * self.ifact[k] * self.ifact[n - k]
    }
}
// ---------- end Precalc ----------
//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,
        m: usize,
    }
    if n <= 2 {
        println!("0");
        return;
    }
    let pc = Precalc::new(n + m);
    let ans = pc.comb(m, n - 1) * ModInt((n - 2) as u32) * ModInt(2).pow((n - 3) as u32);
    println!("{}", ans);
}

fn main() {
    run();
}


use std::io;

fn main() {
    let mut input_str = String::new();
    io::stdin().read_line(&mut input_str).expect("read error");

    let input: Vec<i64>  = input_str.split_whitespace()
        .map(|x| x.parse::<i64>().expect("parse error"))
        .collect();

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

    let mut divisors: Vec<i64> = vec![];
    for divisor in 1..n+1 {
        if divisor * divisor > n { break; }
        if n % divisor == 0 { divisors.push(divisor); }
    }

    let another_divisors: Vec<i64>;
    another_divisors = divisors.iter().map(|x| n / x).filter(|x| x * x != n).rev().collect();

    divisors.extend(another_divisors);

    if (divisors.len() as i64) < k {
        println!("-1");
    } else {
        println!("{}", divisors[k as usize - 1]);
    }
}


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_imports)]
use std::io::stdin;

mod util {
    use std::io::stdin;
    use std::str::FromStr;
    use std::fmt::Debug;

    #[allow(dead_code)]
    pub fn line() -> String {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    }

    #[allow(dead_code)]
    pub fn gets<T: FromStr>() -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|t| t.parse().unwrap())
            .collect()
    }
}

#[allow(unused_macros)]
macro_rules! get {
    ($t:ty) => {
        {
            let mut line: String = String::new();
            stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t:ty),*) => {
        {
            let mut line: String = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            (
                $(iter.next().unwrap().parse::<$t>().unwrap(),)*
            )
        }
    };
    ($t:ty; $n:expr) => {
        (0..$n).map(|_|
                    get!($t)
                   ).collect::<Vec<_>>()
    };
    ($($t:ty),*; $n:expr) => {
        (0..$n).map(|_|
                    get!($($t),*)
                   ).collect::<Vec<_>>()
    };
    ($t:ty ;;) => {
        {
            let mut line: String = String::new();
            stdin().read_line(&mut line).unwrap();
            line.split_whitespace()
                .map(|t| t.parse::<$t>().unwrap())
                .collect::<Vec<_>>()
        }
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

fn main() {
    let (n, a, b) = get!(usize, usize, usize);

    let mut ans = 1;
    for i in 1..n {
        let k = n - i;

        if a >= i && b >= k {
            ans = max(ans, min(a / i, b / k));
        }
    }

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


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

use std::io::prelude::*;
use std::io::BufReader;
use std::cmp::{max, min};

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn get_vec<T>() -> Vec<T>
where T: FromStr,
      <T as FromStr>::Err: std::fmt::Debug,
{
    get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()
}

const N: i64 = 998_244_353;

fn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {
    if b == 0 {
        (a, 1, 0)
    } else {
        let (d0, x0, y0) = extended_euclid(b, a % b);
        (d0, y0, x0 - a / b * y0)
    }
}

fn main() {
    let s = get_line().trim().to_string();

    let names = vec![
        "Danil",
        "Olya",
        "Slava",
        "Ann",
        "Nikita",
    ];

    let count = names.into_iter()
        .map(|name| s.split(name).count() - 1)
        .sum::<usize>();

    if count == 1 {
        println!("YES");
    } else {
        println!("NO");
    }
}


use std::io;
use std::io::prelude::*;

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn main() {
    let (n, t, k, d) = {
        let input = get_line();
        let mut it = input.split_whitespace().map(|k| k.parse::<u32>().unwrap());
        (
            it.next().unwrap(),
            it.next().unwrap(),
            it.next().unwrap(),
            it.next().unwrap(),
            )
    };

    let t1 = (n - 1) / k + 1;

    let ta = d / t;

    if t1 > ta + 1 {
        println!("YES");
    } else {
        println!("NO");
    }
}


fn solve() {
    input! {
        mut s: i32,
    }
    let mut ans = vec![];
    for i in (1..10).rev() {
        if s >= i {
            ans.push(i);
            s -= i;
        }
    }
    for d in ans.into_iter().rev() {
        print!("{}", d);
    }
    println!();
}

fn main() {
    input! {
        t: usize,
    }
    for _ in 0..t {
        solve();
    }
}

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


use std::io;

macro_rules! readln {
    () => {{
        use std::io;
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim().to_string()
    }};
    ( $t:ty ) => {{
        let input = readln!();
        input.parse::<$t>().unwrap()
    }};
    ( $( $t:ty ),+ ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        (
            $(
                input.next().unwrap().parse::<$t>().unwrap(),
            )+
        )
    }}
}

fn main() {
    let (width, height, count) = readln!(i32, i32, i32);

    let mut result = 0;
    for i in 0..count {
        let curr_width = width - 4 * i;
        let curr_height = height - 4 * i;

        result += 2 * (curr_width + curr_height - 2);
    }

    println!("{}", result);
}


use std::io::{self, BufRead, Write};

fn solve<I: BufRead, O: Write>(mut input: I, mut output: O) {
    let from = read_time(&mut input);
    let to = read_time(&mut input);
    let from_minutes = from.0 * 60 + from.1;
    let to_minutes = to.0 * 60 + to.1;
    let mid_minutes = (to_minutes + from_minutes) / 2;
    let mid = (mid_minutes / 60, mid_minutes % 60);
    writeln!(output, "{:02}:{:02}", mid.0, mid.1).unwrap();
}

fn read_time<I: BufRead>(mut input: I) -> (i32, i32) {
    let mut time = String::new();
    input.read_line(&mut time).unwrap();
    let time: Vec<i32> = time.split(':').map(|x| x.trim().parse().unwrap()).collect();
    (time[0], time[1])
}

#[cfg(test)]
mod tests {
    #[test]
    fn example1() {
        assert_eq!(solve("10:00\n11:00\n"), "10:30\n");
    }

    #[test]
    fn example2() {
        assert_eq!(solve("11:10\n11:12\n"), "11:11\n");
    }

    #[test]
    fn example3() {
        assert_eq!(solve("01:02\n03:02\n"), "02:02\n");
    }

    fn solve(input: &str) -> String {
        let mut output = Vec::new();
        super::solve(input.as_bytes(), &mut output);
        String::from_utf8(output).unwrap()
    }
}

fn main() {
    let input = io::stdin();
    let input = input.lock();
    let output = io::stdout();
    let output = output.lock();
    solve(input, output)
}


//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")
    };
}

//

fn gcd(a: u64, b: u64) -> u64 {
    if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}

fn run() {
    input! {
        n: usize,
        p: [usize1; n],
    }
    let mut q = p.clone();
    q.sort();
    q.dedup();
    if q.len() < n {
        println!("-1");
        return;
    }
    let mut a = vec![];
    let mut used = vec![false; n];
    for i in 0..n {
        if used[i] {
            continue;
        }
        used[i] = true;
        let mut k = p[i];
        let mut c = 1;
        while k != i {
            used[k] = true;
            c += 1;
            k = p[k];
        }
        if c % 2 == 0 {
            a.push(c / 2);
        } else {
            a.push(c);
        }
    }
    a.sort();
    let ans = a.iter().fold(1, |s, a| s / gcd(s, *a) * *a);
    println!("{}", ans);
}

fn main() {
    run();
}


#[allow(unused_imports)]
use std::io::{stdin, Read, StdinLock};
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::str::FromStr;
#[allow(unused_imports)]
use std::collections::{HashSet, HashMap, BinaryHeap, VecDeque};
#[allow(unused_imports)]
use std::vec::Vec;

#[allow(dead_code)]
const INF: i32 = 1000_000_000;
#[allow(dead_code)]
const INFLL: i64 = 1000_000_000_000_000_000;
#[allow(dead_code)]
const EPS: f64 = 1.0e-10;
#[allow(dead_code)]
const MOD: i32 = 1000_000_007;
#[allow(dead_code)]
const MODLL: i64 = 1000_000_007;

struct Scanner<'a> {
    cin: StdinLock<'a>,
}

#[allow(dead_code)]
impl<'a> Scanner<'a> {
    fn new(cin: StdinLock<'a>) -> Scanner<'a> {
        Scanner {cin: cin}
    }
    fn read1<T: FromStr>(&mut self) -> Option<T> {
        let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)
                    .skip_while(|c| c.is_whitespace())
                    .take_while(|c| !c.is_whitespace())
                    .collect::<String>();
        token.parse::<T>().ok()
    }
    fn read<T: FromStr>(&mut self) -> T {
        self.read1().unwrap()
    }
}

fn main() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin);

    let _n: usize = sc.read();
    let s: String = sc.read();
    let s: Vec<char> = s.chars().collect();

    fn vowel(c: char) -> bool {
        return c == 'a' || c == 'i' || c == 'e' || c == 'o' || c == 'u' || c == 'y';
    }

    let mut ans: String = String::new();
    let mut last = '0';
    for c in s {
        if ans.len() == 0 {
            ans.push(c);
            last = c;
        } else {
            if vowel(last) && vowel(c) {
                continue;
            }
            ans.push(c);
            last = c;
        }
    }
    println!("{}", ans);
}


fn main() {
    let mut input_line = String::new();
    std::io::stdin()
        .read_line(&mut input_line)
        .expect("Failed to read line");

    let mut parts = input_line.split_whitespace();
    let n: usize = parts.next().expect("Not enough input numbers")
           .parse().expect("Input is not a number");
    let m: usize = parts.next().expect("Not enough input numbers")
           .parse().expect("Input is not a number");

    if m == 1 {
        println!("{}", n - 1)
    } else {
        println!("{}", n * (m - 1));
    }
}