//! http://codeforces.com/problemset/problem/837/A

#[macro_export]
macro_rules! scanln {
  ($($var:ident : $ty:path),+) => {
    $(let $var: $ty;)+
    {
      use std::io;
      let mut __buf = String::new();
      io::stdin().read_line(&mut __buf).unwrap();
      let mut eles = __buf.split_whitespace();
      $($var = Scan::scan(&mut eles);)+
    }
  }
}

pub trait Scan {
  fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator<Item=&'a str>;
}

macro_rules! impl_scan_single {
  ($ty:ty) => {
    impl Scan for $ty {
      fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator<Item=&'a str> {
        let next = eles.next().unwrap();
        match next.parse() {
          Ok(res) => res,
          Err(_) => panic!()
        }
      }
    }
  }
}

impl_scan_single!(u8);
impl_scan_single!(u16);
impl_scan_single!(u32);
impl_scan_single!(u64);
impl_scan_single!(usize);
impl_scan_single!(i8);
impl_scan_single!(i16);
impl_scan_single!(i32);
impl_scan_single!(i64);
impl_scan_single!(isize);
impl_scan_single!(f32);
impl_scan_single!(f64);
impl_scan_single!(String);

const __IMPL_SCAN_FOR_VEC: () = {
  use std::str::FromStr;
  impl<T> Scan for Vec<T> where T: FromStr {
    fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator<Item=&'a str> {
      eles.map(|str| match str.parse() {
        Ok(res) => res,
        Err(_) => panic!()
      }).collect()
    }
  }
};

pub trait CharExt: Copy {
  fn is_digit(self, radix: u32) -> bool;
  fn to_digit(self, radix: u32) -> Option<u32>;
  fn is_alphabetic(self) -> bool;
  fn is_lowercase(self) -> bool;
  fn is_uppercase(self) -> bool;
  fn is_whitespace(self) -> bool;
  fn is_alphanumeric(self) -> bool;
  fn to_lowercase(self) -> Self;
  fn to_uppercase(self) -> Self;
}

macro_rules! impl_u8 {
  ($meth:ident($($arg:ident : $ty:ty),*) -> $ret:ty) => {
    fn $meth(self, $($arg : $ty),*) -> $ret {
      let c = self as char;
      c.$meth($($arg),*)
    }
  }
}

impl CharExt for u8 {
  impl_u8!(is_digit(radix: u32) -> bool);
  impl_u8!(to_digit(radix: u32) -> Option<u32>);
  impl_u8!(is_alphabetic() -> bool);
  impl_u8!(is_lowercase() -> bool);
  impl_u8!(is_uppercase() -> bool);
  impl_u8!(is_whitespace() -> bool);
  impl_u8!(is_alphanumeric() -> bool);
  fn to_lowercase(self) -> Self {
    let c = self as char;
    c.to_lowercase()
      .next()
      .map(|c| c as u8)
      .unwrap_or(self)
  }
  fn to_uppercase(self) -> Self {
    let c = self as char;
    c.to_uppercase()
      .next()
      .map(|c| c as u8)
      .unwrap_or(self)
  }
}

// -----------------------------------------------------------------------------

fn volume(word: &[u8]) -> u32 {
  word.iter()
    .filter_map(|&c| if c.is_uppercase() { Some(()) } else { None })
    .count()
    as u32
}

fn main() {
  use std::io::{self, Write, BufWriter};
  let __stdout = io::stdout();
  let mut __out = BufWriter::with_capacity(4096, __stdout.lock());

  macro_rules! put {
    ($fmt:expr) => { write!(__out, $fmt).unwrap(); };
    ($fmt:expr, $($arg:expr),+) => { write!(__out, $fmt, $($arg),+).unwrap(); }
  }
  macro_rules! putln {
    () => { writeln!(__out, "").unwrap(); };
    ($fmt:expr) => { writeln!(__out, $fmt).unwrap(); };
    ($fmt:expr, $($arg:expr),+) => { writeln!(__out, $fmt, $($arg),+).unwrap(); }
  }
  macro_rules! fflush {
    () => { __out.flush().unwrap(); }
  }

  scanln!(_n: u32);
  scanln!(s: String);
  let mut max_volume = 0;
  for word in s.split_whitespace() {
    let vol = volume(word.as_bytes());
    max_volume = std::cmp::max(vol, max_volume);
  }
  putln!("{}", max_volume);
}


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 volume_of(word: &str) -> usize {
    word.chars().filter(|x| x.is_uppercase()).count()
}

fn main() {
    input! {
        _a: usize,
        s: String,
    }
    println!("{}", s.split(" ").map(|x| volume_of(x)).max().unwrap_or(0));
}


fn read_string() -> String {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed");
    input
}

fn read_int() -> u64 {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed");
    let x = input.trim().parse::<u64>().unwrap();
    input.clear();
    x
}

fn main(){
    let i = read_int() + 2;
    let s = read_string().replace("\n", "").replace("\r", "");
    let vec: Vec<&str> = s.split("").collect();
    let caps = vec!["A","B","C","D","E","F","G","H","I","G","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    let mut max = 0;
    let mut tmp = 0;
    for x in 0..i{
        for cap in 0..caps.len(){
            if vec[x as usize] == caps[cap as usize]{
                tmp = tmp + 1;
            }
        }
        if (vec[x as usize] == " ") || (vec[x as usize] == ""){
            if max < tmp{
                max = tmp;
            }
            tmp = 0;
        }
    }
    println!("{:?}", max);
}


use std::io::{self, prelude::*};
use std::str;
use std::string::String;
use std::collections::LinkedList;
use std::vec::Vec;
use std::cmp;

fn bfs(initial_length: i32, abc_list: Vec<i32>) -> i32 {
    let mut answer: i32 = 0;

    //TODO: BFS, but do not return after the count is 0
    let mut queue: LinkedList<i32> = LinkedList::new();
    queue.push_back(initial_length);

    let mut step: i32 = 0;
    loop {
        if queue.len() == 0 {
            break;
        }

        let size: usize = queue.len();
        for _ in 0..size {
            let current: i32 = queue.pop_front().unwrap();

            if current < 0 {
                continue;
            }

            if current == 0 {
                answer = cmp::max(answer, step);
            }

            //subtract
            for i in 0..abc_list.len() {
                let next_result: i32 = current - abc_list[i];
                queue.push_back(next_result);
            }
        }

        step += 1;
    }

    return answer;
}

#[allow(unused_must_use)]
fn run<B: BufRead, W: Write>(mut reader: Scanner<B>, mut writer: W) {
    let initial_length: i32 = reader.next();

    let mut list: Vec<i32> = Vec::new();
    for _ in 0..3 {
        list.push(reader.next());
    }
    writeln!(writer, "{}", bfs(initial_length, list));
}

fn main() {
    let stdin = io::stdin();
    let stdout = io::stdout();

    let reader = Scanner::new(stdin.lock());
    let writer = io::BufWriter::new(stdout.lock());
    run(reader, writer);
}

pub struct Scanner<B> {
    reader: B,
    buffer_string: Vec<u8>,
    buffer_iterator: str::SplitWhitespace<'static>,
}

impl <B: BufRead> Scanner<B> {
    pub fn new(reader: B) -> Self {
        return Self {
            reader,
            buffer_string: Vec::new(),
            buffer_iterator: "".split_whitespace()
        };
    }

    pub fn next<T: str::FromStr>(&mut self) -> T {
        loop {
            //if buffer already exists, just use existing buffer
            if let Some(token) = self.buffer_iterator.next() {
                return token.parse().ok().expect("Fail to parse token");
            }

            //get new line
            self.buffer_string.clear();
            self.reader.read_until(b'\n', &mut self.buffer_string).expect("Failed to read");

            //split by white space
            self.buffer_iterator = unsafe {
                let slice = str::from_utf8_unchecked(&self.buffer_string);
                std::mem::transmute(slice.split_whitespace())
            };
        }
    }

    pub fn next_line(&mut self) -> String {
        //reset buffer
        self.buffer_iterator = "".split_whitespace();
        self.buffer_string.clear();

        let mut input: String = String::new();
        self.reader.read_line(&mut input).expect("Failed to read line");
        return input.trim().to_string();
    }
}


use std::cmp::max;

fn main() {
    let inp = read_input();
    let (n, a, b, c) = (inp[0], inp[1], inp[2], inp[3]);
    let mut ans = 0;

    ans = max(ans, compute(n, a, b, c));
    ans = max(ans, compute(n, a, c, b));
    ans = max(ans, compute(n, b, a, c));
    ans = max(ans, compute(n, b, c, a));
    ans = max(ans, compute(n, c, a, b));
    ans = max(ans, compute(n, c, b, a));

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

fn compute(mut n: usize, x: usize, y: usize, z: usize) -> usize {
    match n % x % y % z {
        0 => {
            let mut ans = n / x;
            n %= x;
            ans += n / y;
            n %= y;
            ans += n / z;
            ans
        }
        _ => 0,
    }
}

fn read_input() -> Vec<usize> {
    let mut buffer = String::new();

    std::io::stdin()
        .read_line(&mut buffer)
        .expect("Failed to get input");

    buffer
        .trim()
        .split_whitespace()
        .map(|x| x.parse().expect("Failed to parse number"))
        .collect()
}


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

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

macro_rules! debug {($($a:expr),*) => {println!(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")
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}

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 }
}

use std::hash::Hash;
fn inc<T: Hash+Ord>(map:&mut BTreeMap<T,i64>, key:T) {
    let count = map.entry(key).or_insert(0);
    *count += 1;
}

fn int(ch: char) -> i64 {
    return (ch as u8 - b'0') as i64
}

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

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

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

    for i in 0..n+1 {
        for j in 0..3 {
            if i < a[j] { continue; }
            if dp[i-a[j]] == -1 { continue; }
            dp[i] = max(dp[i], dp[i-a[j]]+1);
        }
    }
    //debug!(dp);

    println!("{}", dp[n]);
}

/*

長さ n のリボンを a,b,c のいずれかの長さにする。
このとき、最大のリボンの数を求める。

dp[i] := 長さ i のリボンを切れる最大の数
dp[i] = max(dp[i-a[j]]+1, j=0,1,2)

*


fn minimun_cuts(n: i32, options: &[i32]) -> i32 {
    let mut table = vec![vec![-1; options.len()]; n as usize + 1];

    fn traverse(mut n: i32, options: &[i32], table: &mut Vec<Vec<i32>>) -> i32 {
        for (i, option) in options.iter().enumerate() {
            if table[n as usize][i] == -1 {
                let mut push_value = -900;
                let conditional = n - option;
                if conditional == 0 {
                    push_value = 1;
                } else if conditional > 0 {
                    n -= option;
                    push_value = 1 + traverse(n, options, table);
                    n += option;
                }
                table[n as usize][i] = push_value;
            }
        }
        *table[n as usize].iter().max().unwrap()
    }

    traverse(n, options, &mut table)
}

fn main() {
    let mut variables = String::new();
    std::io::stdin().read_line(&mut variables).unwrap();
    let variables: Vec<i32> = variables
        .split_whitespace()
        .map(|string| string.trim().parse().ok().unwrap())
        .collect();
    let n = variables[0];
    let (a, b, c) = (variables[1], variables[2], variables[3]);
    println!("{}", minimun_cuts(n, &[a, b, c]));
}


// 992C
use std::io;

fn main() {
    let (x, k) = read_2::<u64>(&io::stdin());
    let modulo = 1000000007;
    if x == 0 {
        println!("{}", x);
        return;
    }
    let a = (mod_exp(2, k + 1, modulo) * x) % modulo;
    let b = mod_exp(2, k, modulo);
    if a >= b {
        println!("{}", (a - b + 1) % modulo);
    } else {
        println!("{}", (modulo + (a - b) + 1) % modulo);
    }
}

fn mod_exp(mut a: u64, mut k: u64, n: u64) -> u64 {
    let mut multiplier = 1;
    a = a % n;
    while k != 0 {
        if k % 2 == 0 {
            a = (a * a) % n;
        } else {
            multiplier = (multiplier * a) % n;
            a = (a * a) % n;
        }
        k = k / 2;
    }
    multiplier as u64
}

fn read_2<T>(stdin: &io::Stdin) -> (T, T)
where
    T: std::str::FromStr,
    <T as std::str::FromStr>::Err: std::fmt::Debug,
{
    let mut s = String::new();
    stdin.read_line(&mut s).unwrap();
    let mut iter = s.trim().split_whitespace().map(|x| x.parse().unwrap());
    (iter.next().unwrap(), iter.next().unwrap())
}


//! http://codeforces.com/contest/732/problem/A

fn main() {
  use std::io;
  let mut buf = String::new();
  io::stdin().read_line(&mut buf).unwrap();
  let mut ns = buf.split(" ")
    .map(|str| str.trim().parse::<u32>().unwrap());
  let k = ns.next().unwrap();
  let r = ns.next().unwrap();
  let mut i = 1;
  loop {
    if ((i * k) - r) % 10 == 0 { break; }
    if (i * k) % 10 == 0 { break; }
    i += 1;
  }
  println!("{}", i);
}


use std::io;

fn main() {
    let mut s = String::new();
    io::stdin()
        .readln(&mut s)
        .unwrap();

    let words = s
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    for i in 1..10 {
        if i * words[0] % 10 == words[1] || i * words[0] % 10 == 0 {
            println!("{}", i);
            break;
        }
    }
}


use std::io;
pub struct Scanner<B> {
    reader: B,
    buffer: Vec<String>,
}

impl<B: io::BufRead> Scanner<B> {
    pub fn new(reader: B) -> Scanner<B> {
        Scanner {
            reader: reader,
            buffer: Vec::new(),
        }
    }

    /// Use "turbofish" syntax next::<T>() to select data type of next token.
    pub fn next<T: ::std::str::FromStr>(&mut self) -> T
    where
        T::Err: ::std::fmt::Debug,
    {
        if let Some(front) = self.buffer.pop() {
            front.parse::<T>().expect(&front)
        } else {
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Line not read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
            self.next()
        }
    }
}

fn main1() {
    let stdin = io::stdin();
    let mut input = Scanner::new(stdin.lock());
    let k = input.next::<i64>();
    let r = input.next::<i64>();
    for i in 1..10 {
        if (i * k % 10) == r {
            println!{"{}", i};
            return;
        }
    }
    println!["10"];
}

fn main() {
    std::thread::Builder::new().stack_size(50 << 20)
        .spawn(main1).unwrap().join().unwrap();
}


#![allow(unused_imports)]
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::str::FromStr;
use std::collections::{VecDeque, HashMap};

fn main() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let nums = get_numbers(&line);
    let shovel_price: u32 = nums[0];
    let change = nums[1];

    for i in 1..11 {
        let total = i * shovel_price;
        if total % 10 == 0 || (total - change) % 10 == 0 {
            println!("{}", i);
            return;
        }
    }

    println!("-1");
}

/*
 * Utility Functions
 */

// get numbers from line seperated by spaces
fn get_numbers<T>(line: &str) -> Vec<T>
    where T: FromStr,
          <T as std::str::FromStr>::Err: std::fmt::Debug,
{
    line.split_whitespace()
        .map(|chunk| chunk.parse::<T>().expect("failed to parse"))
        .collect()
}


use std::io::stdin;
fn main() {
    let mut input = String::new();
    stdin().read_line(&mut input).unwrap();
    let distance: i32 = input.trim().parse().unwrap();

    if distance <= 5 {
        println!("1");
    } else if distance % 5 == 0 {
        println!("{}", distance % 5);
    } else {
        println!("{}", distance % 5 + 1);
    }
}


use std::io::stdin;
use std::cmp::min;

fn main() {
    let mut input = String::new();
    stdin().read_line(&mut input).unwrap();
    let nposlr = input.split_whitespace().map(|x| x.parse::<i32>().unwrap()).collect::<Vec<_>>();
    let (n, pos, l, r) = (nposlr[0], nposlr[1], nposlr[2], nposlr[3]);

    if l == 1 && r == n {
        println!("0");
    } else if l == 1 {
        println!("{}", (pos - r).abs() + 1);
    } else if r == 1 {
        println!("{}", (pos - l).abs() + 1);
    } else {
        let min_dist = min((pos - l).abs(), (pos - r).abs());
        println!("{}", min_dist + (r - l).abs() + 2);
    }

}


use std::io;

fn main() {
    let mut a_str = String::new();
    io::stdin().read_line(&mut a_str).expect("read error");
    let mut numbers = a_str.split_whitespace()
        .map(|x| x.parse::<i32>().expect("parse error"))
        .collect::<Vec<i32>>();
    let n = numbers[0];
    let pos = numbers[1];
    let l = numbers[2];
    let r = numbers[3];

    let mut res = 0;

    if l != 1 && r == n {
        res += (pos - l).abs() + 1;
    } else if r != n && l == 1 {
        res += (r - pos).abs() + 1;
    } else if r == n && l == 1{
        res = 0;
    } else {
        if (pos - l).abs() < (r - pos).abs() {
            if l != r {
                res += r - l - 1 + 2 * (pos - l).abs() + 2;
            } else {
                res += (pos - l).abs() + 2;
            }
        } else {
            if l != r {
                res += r - l - 1 + 2 * (r - pos).abs() + 2;
            } else {
                res += (r - pos).abs() + 2;
            }
        }
    }
    println!("{}", res);
}


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

const DECIMAL_RADIX : u64 = 10;

fn read_line(stdin : &Stdin, line : &mut String) {
    match stdin.read_line(line) {
        Ok(_) => return,
        Err(msg) => panic!("Could not read line! Message: {}.", msg),
    }
}

fn parse_t<T : FromStr>(s : &str) -> T {
    match s.trim().parse() {
        Ok(y) => y,
        Err(_) => panic!("Could not read from string!"),
    }
}

fn read_t<T : FromStr>(stdin : &Stdin) -> T {
    let mut line = String::new();
    read_line(stdin, &mut line);
    parse_t(&line)
}

fn little_endian_digits(n : u64, ds : &mut Vec<u64>) {
    let mut x = n;
    loop {
        let d = x % 10;
        x = x / 10;
        ds.push(d);
        if x == 0 {
            break;
        }
    }
}

fn big_endian_digits(n : u64, ds : &mut Vec<u64>) {
    little_endian_digits(n, ds);
    ds.reverse();
}

fn big_endian_digits_to_number(ds : &Vec<u64>) -> u64 {
    let mut x = 0;
    for d in ds {
        x = (x * 10) + d;
    }
    x
}

fn contains(y : u64, xs : &Vec<u64>) -> bool {
    for &x in xs {
        if y == x {
            return true;
        }
    }
    false
}

fn find_replacement_digit(d : &Option<u64>, digits : &Vec<u64>) -> Option<u64> {
    let mut s = 0;
    match *d {
        None => (),
        Some(y) => {
            s = y + 1;
        },
    }
    for i in s .. DECIMAL_RADIX {
        if contains(i, digits) {
            // Do nothing ...
        } else {
            return Some(i);
        }
    }
    None
}

fn next_with_distinct_digits(n : u64) -> u64 {
    let mut b_e_digits = vec![];
    big_endian_digits(n, &mut b_e_digits);
    let orig_level = b_e_digits.len() - 1;
    let mut level = orig_level;
    let mut c_d_o = Some(b_e_digits[level]);
    loop {
        let r_d_o = find_replacement_digit(&c_d_o, &b_e_digits);
        match r_d_o {
            None => {
                b_e_digits.pop();
                level = level - 1;
                c_d_o = Some(b_e_digits[level]);
            },
            Some(r_d) => {
                b_e_digits[level] = r_d;
                if level < orig_level {
                    b_e_digits.push(DECIMAL_RADIX);
                }
                level = level + 1;
                c_d_o = None;
            }
        }
        if level > orig_level {
            break;
        }
    }
    big_endian_digits_to_number(&b_e_digits)
}

fn main() {
    let stdin = io::stdin();
    let n = read_t(&stdin);
    println!("{}", next_with_distinct_digits(n));
}


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

#[allow(unused_macros)]
macro_rules! m {
    ($c:tt, $x:expr, $y:expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
#[allow(unused_macros)]
macro_rules! l {
    ($i:ident . $e:tt : $t:ty, $($a:ident),*) => {
        $( let $a: $t = $i.$e(); )*
    };
    ($i:ident . $e:tt, $($a:ident),*) => {
        $( let $a = $i.$e(); )*
    };
}

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 f(&mut self) ->    f64 { 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 ip<T: FromStr>(&mut self, n: usize) -> impl std::iter::Iterator<Item=T> where T::Err: Debug {
        //(0..n).map(|_| self.p())
        self.vp(n).into_iter()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}

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

    l!(input.i, a, b);
    if (a - b).abs() <= 1 {
        println!("YES");
    } else {
        println!("NO");
    }
}


macro_rules! read_line {
    ($v:ident) => {
        let mut temp = String::new();
        std::io::stdin().read_line(&mut temp).unwrap();
        let $v = temp;
    };
    (var, $t:ty, $($v:ident), *) => {
        read_line!(input_line);
        let mut iter = parse_token!($t, input_line);
        $(
            let $v = iter.next().unwrap();
        )*
    };
    (vec, $t:ty, $v:ident) => {
        read_line!(input_line);
        let iter = parse_token!($t, input_line);
        let $v: Vec<$t> = iter.collect();
    };
    ($($v:ident; $t:ty), *) => {
        read_line!(input_line);
        let mut iter = input_line.split_whitespace();
        $(
            let $v: $t = iter.next().unwrap().parse().unwrap();
        )*
    };
}

macro_rules! parse_token {
    ($t:ty, $e:expr) => {
        $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());
    };
}

fn main() {
    read_line!(even;u64, odd;u64);
    if odd == even || odd = even + 1 {
        println!("YES")
    } else {
        println!("NO")
    }
}


macro_rules! read_line {
    ($v:ident) => {
        let mut temp = String::new();
        std::io::stdin().read_line(&mut temp).unwrap();
        let $v = temp;
    };
    (var, $t:ty, $($v:ident), *) => {
        read_line!(input_line);
        let mut iter = parse_token!($t, input_line);
        $(
            let $v = iter.next().unwrap();
        )*
    };
    (vec, $t:ty, $v:ident) => {
        read_line!(input_line);
        let iter = parse_token!($t, input_line);
        let $v: Vec<$t> = iter.collect();
    };
    ($($v:ident; $t:ty), *) => {
        read_line!(input_line);
        let mut iter = input_line.split_whitespace();
        $(
            let $v: $t = iter.next().unwrap().parse().unwrap();
        )*
    };
}

macro_rules! parse_token {
    ($t:ty, $e:expr) => {
        $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());
    };
}

fn main() {
    read_line!(even;i64, odd;i64);
    if odd == 0 && even == 0{
        println!("NO") // There must be one staircase
    }
    if (odd - even).abs() <= 1 { // Valid count
        println!("YES")
    } else {
        println!("NO")
    }
}


#![allow(unused_imports)]
use std::io::{ self, Write };
use std::str::FromStr;
use std::cmp::{ min, max };
use std::collections::{ BinaryHeap, VecDeque };

macro_rules! trace {
    ($var:expr) => ({
        let _ = writeln!(&mut std::io::stderr(), ">>> {} = {:?}", stringify!($var), $var);
    })
}
macro_rules! swap { ($a:expr, $b:expr) => ({ let t = $b; $b = $a; $a = t; }) }

fn main() {
    let mut sc = Scanner::new();
    let a: i32 = sc.cin();
    let b: i32 = sc.cin();

    let k = if a == b || a + 1 == b { "YES" } else { "NO" };
    println!("{}", k);

}

#[allow(dead_code)]
struct Scanner { stdin: io::Stdin, buffer: VecDeque<String>, }
#[allow(dead_code)]
impl Scanner {
    fn new() -> Scanner { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } }
    fn reserve(&mut self) {
        while self.buffer.len() == 0 {
            let mut line = String::new();
            let _ = self.stdin.read_line(&mut line);
            for w in line.split_whitespace() {
                self.buffer.push_back(String::from(w));
            }
        }
    }
    fn cin<T: FromStr>(&mut self) -> T {
        self.reserve();
        match self.buffer.pop_front().unwrap().parse::<T>() {
            Ok(a) => a,
            Err(_) => panic!("parse err")
        }
    }
    fn get_char(&mut self) -> char {
        self.reserve();
        let head = self.buffer[0].chars().nth(0).unwrap();
        let tail = String::from( &self.buffer[0][1..] );
        if tail.len()>0 { self.buffer[0]=tail } else { self.buffer.pop_front(); }
        head
    }
}


#[derive(Debug)]
struct RhombusIterator{
    current: isize,
    count: isize,
    total: isize,
}

impl RhombusIterator{
    pub fn new() ->Self{
        RhombusIterator{
            current: 1,
            count: 0,
            total: 1,
        }
    }
}

impl Iterator for RhombusIterator{
    type Item = isize;

    fn next(&mut self) -> Option<Self::Item> {
        match self.current{
            1 => {},
            _ => {
                self.total += 2* self.current + (2* self.count);
                self.count += 1;
            },
        }
        self.current +=1;
        Some(self.total)
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {

    //parse
    let mut input = String::new();
    std::io::stdin().read_line(&mut input)?;
    let input: usize = input.trim().parse().expect("Invalid input parameter");

    //solve
    let result = solve(input);

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

    Ok(())
}

fn solve(input: usize) -> isize{
    let iter = RhombusIterator::new();
    iter.skip(input-1).inspect(|s| println!("Input: {}, Current: {}", input, s)).next().expect("Could not calc rhombus")
}

#[cfg(test)]
mod test{
    use super::solve;

    #[test]
    fn test1() {

        assert_eq!(1, solve(1));
        assert_eq!(5, solve(2));
        assert_eq!(solve(3), 13);
        assert_eq!(25, solve(4));
        assert_eq!(41, solve(5));
    }
}


use std::cmp::{max, min};
use std::io::{stdin, stdout, BufWriter, Write};

#[derive(Default)]
struct Scanner {
    buffer: Vec<String>,
}
impl Scanner {
    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();
            stdin().read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let mut scanner = Scanner::default();

    let n = scanner.next::<usize>();

    let mut dp = vec![1];

    for i in 1..n {
        dp.push(dp[i - 1] + i * 4);
    }

    println!("{:?}", dp);
}


fn main() {
    let str = "010";
    let trimmed = str.trim();
    let mut negative = false;
    let mut lookup = &trimmed[..];
    if trimmed.starts_with('-') {
        negative = true;
        lookup = &trimmed[1..];
    }
    if trimmed.starts_with('+') {
        negative = false;
        lookup = &trimmed[1..];
    }

    let digits = lookup.chars().take_while(|c| c.is_digit(10)).collect::<Vec<_>>();
    let mut answer: i64 = 0;

    for d in digits.iter().map(|c| c.to_digit(10).unwrap()) {
        answer *= 10;

        answer += match negative {
            true => -1 * d as i64,
            false => d as i64,
        };

        if answer >= i32::max_value().into() {
            answer = i32::max_value() as i64;
            break;
        }
        if answer <= i32::min_value().into() {
            answer = i32::min_value() as i64;
            break;
        }
    }

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


use std::io::stdin;

fn main()
{
    //handle input / output
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let card: Vec<_> = s.split_whitespace().collect();
    let card = card[0].clone().chars().collect::<Vec<_>>();
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let deck: Vec<_> = s.split_whitespace().collect();
    let deck = deck.iter().map( |c| c.chars().collect::<Vec<_>>()).collect::<Vec<_>>();

    for dc in deck {
        if dc[0] == card[0] || dc[1] == card[1] {
            println!("YES");
            return;
        }
    }

    println!("N");
}


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

fn get_nums() -> Vec<i32> {
	let mut input = String::new();

	io::stdin().read_line(&mut input)
		.expect("");

	input.trim()
		.split_whitespace()
		.map(|d| i32::from_str(d).unwrap())
		.collect::<Vec<_>>()
}

fn get_quad() -> (i32, i32, i32, i32) {
	let v = get_nums();

	(v[0], v[1], v[2], v[3])
}

fn main() {
 	let (n, t, mut k, d) = get_quad();

 	let mut t1 = 0;
 	let mut c = 0;

 	while c < n {
 		t1 += t;
 		c += k;
	}

	let mut t2 = 0;
	c = 0;

	if d > k {
		t2 += d;

		for _ in 0..d/t {
			c += k;
		}
		k *= 2;
	} else {
		t2 += t;
		c += k;
	}

	while c < n {
		t2 += t;
		c += k;
	}

	if t1 > t2 {
		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(),
            )
    };

    // n + r = k * x;
    // n = k * x - r ; k < -r <= 0
    // n = k * x + r ; k < r <= 0
    // n + k - 1 = k * x + r ; 0 <= r < k
    // n - 1 = k * (x - 1) + r

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

    let ta = d / t;
    let tb = t1 - ta;

    if tb > 1 {
        println!("YES");
    } else {
        println!("NO");
    }
}


fn input_split() -> Vec<u8> {
    let mut buf = String::with_capacity(7);
    std::io::stdin().read_line(&mut buf).unwrap();
    buf.trim()
        .split_whitespace()
        .map(|elem| elem.parse().unwrap())
        .collect()
}

fn main() {
    let mut shoes = input_split();
    shoes.sort_unstable();
    shoes.dedup();
    println!("{}", 4 - shoes.len());
}


#[allow(unused_imports)] use std::{*, io::*, cmp::*, char::* };
#[allow(unused)] 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)*} }; }
#[allow(unused)] 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)*} }; }
#[allow(unused)] 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")};}
#[allow(unused)] macro_rules! debug { ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap()); }
#[allow(unused)] macro_rules! debugln { ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap()); }

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    #[allow(unused)] macro_rules! puts { ($($format:tt)*) => (let _ = write!(out,$($format)*);); }

    let s1: Vec<char> = get_word().chars().collect();
    let s2: Vec<char> = get_word().chars().collect();

    let mut sum1 = 0;
    let mut sum2 = 0;

    for c in s1 {
	sum1 += match c {
	    '+' => 1,
	    '-' => -1,
	    _  => 0,
	}
    }

    for c in &s2 {
	sum2 += match *c {
	    '+' => 1,
	    '-' => -1,
	    _  => 0,
	}
    }

    let mut q = 0;

    for c in &s2 {
	if *c == '?' {
	    q += 1;
	}
    }

    let d: i64 = sum1 - sum2;
    let d = d.abs();

    let mut  num = 1;

    if d > q || d * q % 2 != 0 { puts!("{}", 0.0); } else {

	let m = d + (q - d) / 2;
	for i in (q - m + 1)..(q + 1) {
	    num *= i;
	}

	puts!("{}", num as f64 / (1 << q) as f64);
    }
}
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();
}

#[allow(dead_code)]
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() }

// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8


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 _main() {
    let mut scan = Scan::new();
    let sent: String = scan.next();
    let received: String = scan.next();
    let mut pos: isize = 0;
    for mov in sent.chars() {
        if mov == '+' {
            pos += 1;
        } else if mov == '-' {
            pos -= 1;
        }
    }
    let mut new_pos: isize = 0;
    let mut unknown: isize = 0;
    for mov in received.chars() {
        if mov == '+' {
            new_pos += 1;
        } else if mov == '-' {
            new_pos -= 1;
        } else {
            unknown += 1;
        }
    }
    let needed = pos - new_pos;
    if needed > unknown {
        println!("{:.5}", 0.0f64);
    } else {
        let total: usize = 2usize.pow(unknown as u32);
        let mut valid = 0isize;
        for i in 0..total {
            if (2 * i.count_ones() as isize - unknown as isize) == needed {
                valid += 1;
            }
        }
        let result = (valid as f64) / (total as f64);
        println!("{:.5}", result);
    }
}

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


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! min {
	($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};
}
#[allow(unused_macros)] macro_rules! max {
	($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! v {
	([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};
	([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: v!([]), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = v!([8]);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn vvb(&mut self, r: usize, c: Option<usize>) -> Vec<Vec<u8>> {
		let mut res = v!([r]);
		let c = c.unwrap_or(0);
		rep!{[r]
			let t = self.vb();
			assert!(c == 0 || t.len() == c);
			res.push(t);
		}
		res
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
	fn graph(&mut self, n: usize, m: usize) -> Vec<Vec<usize>> {
		let mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); e[a].push(b); e[b].push(a); } e
	}
	fn graph_w<T: Copy+FromStr>(&mut self, n: usize, m: usize) -> Vec<Vec<(usize,T)>> where T::Err: Debug {
		let mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); let c: T = self.p(); e[a].push((b,c)); e[b].push((a,c)); } e
	}
}
//------------------- End rusT }}}

// Field (mod prime) {{{
mod field {
	use std::ops::*;
	#[allow(dead_code)] pub const Z0: Field = Field(0);
	#[allow(dead_code)] pub const Z1: Field = Field(1);
	const P5: i32 = 1_000_000_007;
	const P6: i64 = P5 as i64;
	#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] pub struct Field(i32);
	#[allow(dead_code)] impl Field {
		pub fn new<T: Into<i64>>(a: T) -> Self { Self(Self::cv(a)) }
		pub fn new_unchecked(a: i32) -> Self { Self(a) }
		fn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }
		fn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }
		fn cv<T: Into<i64>>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }
		pub fn inv(self) -> Self { self.pow(P5-2) }
		pub fn pow<T: Into<i64>>(self, b: T) -> Self {
			let b = b.into(); if b == 0 { Self(1) } else {
				let mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res
			}
		}
	}
	impl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}
	impl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}
	impl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}
	impl Div for Field { type Output = Self; fn div(self, a: Self) -> Self::Output { self * a.inv() }}
	impl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}
	impl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }
	impl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }
	impl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }
	impl DivAssign for Field { fn div_assign(&mut self, a: Self) { *self = *self / a; } }
	use std::fmt::{Display, Formatter, Result};
	impl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.0) } }
}
#[allow(unused_imports)] use field::{Field, Field as Z, Z0, Z1};
//}}}
// Square Matrix (Field) {{{
type MatT = Field;
const MAT_T_0: MatT = Z0;
const MAT_T_1: MatT = Z1;
#[derive(Debug,Clone)] struct Mat { n: usize, a: Vec<MatT> }
#[allow(dead_code)] impl Mat {
	fn new(n:usize)->Self{Self{n,a:vec![MAT_T_0;n*n]}}
	fn diag(n:usize,v:MatT)->Self{let mut m=Self::new(n);let mut p=0;for _ in 0..n{m.a[p]=v;p+=n+1;}m}
	fn pow(&self,n:u64)->Self{if n==0{Self::diag(self.n,MAT_T_1)}else{let mut t=self.pow(n/2);t*=t.clone();if n%2==1{t*=self.clone();}t}}
	fn range(&self,r:Range<usize>,c:Range<usize>)->Vec<Vec<MatT>>{if r.start<r.end||c.start<c.end{Vec::new()}else{let mut res=vec![vec![MAT_T_0;c.end-c.start];r.end-r.start];
		for i in r.start..r.end{let ir=i-r.start;let ii=i*self.n+c.start;for j in 0..c.end-c.start{res[ir][j]=self.a[ii+j];}}res}}
	fn at(&self,r:usize,c:usize)->MatT{self.a[r*self.n+c]}
	fn at_mut<'a>(&'a mut self,r:usize,c:usize)->&'a mut MatT{&mut self.a[r*self.n+c]}//'
}
impl Mul for Mat{type Output=Self;fn mul(self,o:Self)->Self::Output{assert!(self.n==o.n);let n=self.n;let mut res=Self::new(n);
	for ii in(0..n).map(|i|i*n){for j in 0..n{let mut t=MAT_T_0;let mut kk=j;for k in 0..n{t+=self.a[ii+k]*o.a[kk];kk+=n;}res.a[ii+j]=t;}}res}}
impl Add for Mat{type Output=Self;fn add(mut self,o:Self)->Self{self+=o;self}}
impl Sub for Mat{type Output=Self;fn sub(mut self,o:Self)->Self{self-=o;self}}
impl MulAssign for Mat{fn mul_assign(&mut self,a:Self){*self=self.clone()*a;}}
impl AddAssign for Mat{fn add_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x+=y;}} }
impl SubAssign for Mat{fn sub_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x-=y;}} }
impl PartialEq for Mat{fn eq(&self,o:&Self)->bool{self.n==o.n&&self.a==o.a}}impl Eq for Mat{}
// }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();

	l!(n,m,l,r = rin.l());
	let b = (n*m+1)/2;
	let w = n*m/2;
	let o = Z::new((r+1)/2 - l/2);
	let e = Z::new(r/2 - (l-1)/2);
	let mut mat = Mat::new(2);
	*mat.at_mut(0,0) = e;
	*mat.at_mut(0,1) = o;
	*mat.at_mut(1,0) = o;
	*mat.at_mut(1,1) = e;
	let bm = mat.pow(b as u64);
	let bw = mat.pow(w as u64);
	let sol = bm.at(0,1) * bw.at(0,1) + bm.at(1,1) * bw.at(1,1);
	writeln!(rout, "{}", sol).ok();
}


use std::io;

fn main() {
    let mut ss: String = String::new();
    io::stdin().read_line(&mut ss).unwrap();
    let n: isize = ss.trim().parse().unwrap();

    let mut s: String = String::new();
    io::stdin().read_line(&mut s).unwrap();
    io::stdin().read_line(&mut s).unwrap();
    let v: Vec<usize> = s.trim()
        .split(' ')
        .map(|n| n.parse().unwrap())
        .collect();

    let mut g = vec![0.0; 4];

    for a in v.iter() {
        g[a - 2] += 1.0;
    }

    let cg = ((g[0]*2.0 + g[1]*3.0 + g[2]*4.0 + g[3]*5.0) / n as f32) + 0.5;

    let agg = vec![
        3.0/n as f32,
        2.0/n as f32,
        1.0/n as f32,
    ];

    // println!("{}", cg);
    // println!("{:?}", agg);

    let mut sol = 5.0 - cg;
    if sol <= 0.0 {
        println!("0");
        return;
    } else {
        let mut nn = (sol / agg[0] - 0.00001).ceil();
        // println!("{} {} {}", sol, agg[0], sol / agg[0]);
        if nn <= g[0] {
            println!("{}", nn);
            return;
        }
        sol -= g[0] * agg[0];

        nn = (sol / agg[1] - 0.0001).ceil();
        if nn <= g[1] {
            println!("{}", nn + g[0]);
            return;
        }
        sol -= g[1] * agg[1];

        nn = (sol / agg[2] - 0.00001).ceil();
        if nn <= g[2] {
            println!("{}", nn + g[0] + g[1]);
            return;
        }

        println!("{}", g[0] + g[1] + g[2]);
    }
}


//spnauti-rusT
use std::io::*;
use std::str::{self,*};
use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_macros)]
macro_rules! m {
    ($c:tt, $x:expr, $y:expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
#[allow(unused_macros)]
macro_rules! l {
    ($($v:ident),* = $i:ident.$f:ident $a:tt) => {
        $( let $v = $i.$f$a; )*
    };
    ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {
        $( let $v:$t = $i.$f$a; )*
    };
}
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 f(&mut self) ->    f64 { self.p()                }
    fn u(&mut self) ->  usize { self.p()                }
    fn sk(&mut self, n: usize) { self.it.nth(n - 1); }
    fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> {
        self.ip(n).into_iter()
    }
    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 ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
        self.vp(n).into_iter()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}
//------------------- End rusT

//------------------- Start Field
const P5: i32 = 1_000_000_007;
const P6: i64 = P5 as i64;
#[derive(Debug,Clone,Copy)]
struct Field(i32);
#[allow(dead_code)]
impl Field {
    fn new<T: Into<i64>>(a: T) -> Self { Self(Self::cv(a)) }
    fn new_unchecked(a: i32) -> Self { Self(a) }
    fn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }
    fn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }
    fn cv<T: Into<i64>>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }
}
impl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}
impl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}
impl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}
impl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}
impl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }
impl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }
impl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }
use std::fmt::{Display, Formatter, Result};
impl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.0) } }
// impl Default for Field { fn default() -> Self { Field(0) }}
impl Default for &Field { fn default() -> Self { &Field(0) }}
impl PartialEq for Field { fn eq(&self, a: &Self) -> bool { self.0 == a.0 } }
impl PartialOrd for Field { fn partial_cmp(&self, a: &Self) -> Option<Ordering> { Some(self.0.cmp(&a.0)) } }
impl Eq for Field {}
impl Ord for Field { fn cmp(&self, a: &Self) -> Ordering { self.0.cmp(&a.0) } }
impl Sum<Self> for Field {
    fn sum<I>(i: I) -> Self where I: Iterator<Item = Self> {
        i.fold(Field(0), |a,b| a + b) } }
impl<'a> Sum<&'a Self> for Field {
    fn sum<I>(i: I) -> Self where I: Iterator<Item = &'a Self> {
        i.fold(Field(0), |a,&b| a + b) } }
impl Product<Self> for Field {
    fn product<I>(i: I) -> Self where I: Iterator<Item = Self> {
        i.fold(Field(1), |a,b| a * b) } }
impl<'a> Product<&'a Self> for Field {
    fn product<I>(i: I) -> Self where I: Iterator<Item = &'a Self> {
        i.fold(Field(1), |a,&b| a * b) }
}
//------------------- End Field

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

    const MAX_N: usize = 104;
    const MAX_K: usize = 12;

    let id = |n1, n2, w, k| {
        ((n1 * MAX_N + n2) * 2 + w) * MAX_K + k
    };
    let mut dp = vec![Field::new_unchecked(0); MAX_N * MAX_N * 2 * MAX_K];

    l!(n1,n2,k1,k2 = input.u());
    let k = [k1, k2];
    dp[id(0,0,0,0)] = Field::new_unchecked(1);

    for i in 0..=n1 {
        for j in 0..=n2 {
            for w in 0..=1 {
                let wk = k[w];
                for l in 0..=wk {
                    let val = dp[id(i, j, w, l)];
                    if val.0 == 0 {
                        continue;
                    }
                    for a in 0..=1 {
                        let ii = i + 1 - a;
                        let jj = j + a;
                        let ll = if a == w {l + 1} else {1};
                        dp[id(ii, jj, a, ll)] += val;
                    }
                }
            }
        }
    }

    let mut sol = Field::new_unchecked(0);
    for w in 0..=1 {
        for l in 0..=k[w] {
            sol += dp[id(n1, n2, w, l)];
        }
    }
    println!("{}", sol);
}


fn main() {
    let mut first_input = String::new();
        std::io::stdin()
                    .read_line(&mut first_input)
                    .expect("Value not found");

    let inputs: Vec<usize> = first_input
                                .split_whitespace()
                                .map(|s| s.parse()
                                        .expect("Value not found"))
                                .collect();

    let m: usize = inputs[0];
    let n: usize = inputs[1];

    if (n > m) || (m >16) || (n < 1) || (m < 1) {
        return()
    }
    let boxes = n * m;
    println!("{}", boxes / 2);
}


use std::io;
use std::str::FromStr;
use std::io::prelude::*;

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

fn main() {
    let (k, p): (usize, usize) = {
        let input = get_line();
        let mut it = input.split_whitespace()
            .map(|x| x.parse().unwrap());
        (
            it.next().unwrap(),
            it.next().unwrap(),
            )
    };

    let p = p as u64;

    let mul = |a, b| {
        (a * b) % p
    };

    let pow10 = |k| {
        let mut ret_val = 1;
        for _ in 0..k {
            ret_val = mul(ret_val, 10);
        }
        ret_val
    };

    let mut ans = 0;

    for i in (1..).take(k) {
        let s = format!("{}", i);
        let n = s.len() as u64;
        for (ind, d) in s.bytes().rev().enumerate() {
            let d = ( d - b'0') as u64;
            let ind = ind as u64;
            ans = (ans + d * pow10(ind)) % p;
            ans = (ans + d * pow10(2 * n - 1 - ind)) % p;
        }
    }

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

struct Solver {
}

impl Solver {
}


use std::cmp::Ordering;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let (n, k) = {
        let temp: Vec<u32> = buf
            .trim()
            .split_whitespace()
            .map(|a| a.parse().unwrap())
            .collect();
        (temp[0], temp[1])
    };

    let (mut index, mut jump) = (n / 2, n / 2);
    loop {
        let sum_n = index * (index + 1) / 2;
        let eaten = n - index;

        if eaten > sum_n {
            if jump == 0 {
                index = 1;
                break;
            }
            index += jump;
            jump /= 2;
            continue;
        }

        match k.cmp(&(sum_n - eaten)) {
            Ordering::Equal => break,
            Ordering::Greater => {
                jump /= 2;
                index += jump;
            }
            Ordering::Less => {
                jump /= 2;
                index -= jump;
            }
        }
    }

    println!("{}", n - index);
}


fn main() {
   let mut s = String::new();
   std::io::stdin().read_line(&mut s).unwrap();
   let n : i32 = s.trim().parse().unwrap();
   s = String::new();
   std::io::stdin().read_line(&mut s).unwrap();
   let m : i32 = s.trim().parse().unwrap();
   if m == n {
        println!("YES\n0");
   } else {
        let l = ((m as f64).log(n as f64)) as i32;
        if ((n as f32).powi(l)) as i32 == m {
            println!("YES\n{}",l-1);
        } else {
            println!("NO");
        }
    }

 }


fn input_split() -> Vec<u16> {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    buf.trim()
        .split_whitespace()
        .map(|elem| elem.parse().unwrap())
        .collect()
}

fn determine_b(v: &[u16]) -> Option<u16> {
    let sum: u16 = v.iter().sum();
    if sum % 5 == 0 {
        Some(sum / 5)
    } else {
        None
    }
}

fn print(res: Option<u16>) {
    match res {
        Some(val) => print!("{}", val),
        None => print!("-1"),
    }
}

fn main() {
    print(determine_b(&input_split()))
}


//spnauti-rust
#[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 }
    }};
}
use std::str::*;
use std::fmt::Debug;
struct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: std::io::Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).unwrap();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, std::io::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 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()
    }
}

fn main() {
    let mut buffer = String::new();
    let mut input = WordReader::from_stdin(&mut buffer);

    let sum = (0..5).map(|_| input.i()).sum::<i32>();
    let sol = if sum % 5 == 0 {
        sum / 5
    } else {
        -1
    };
    println!("{}", sol);
}


#[allow(unused_imports)]
use std::cmp::{max,min};

#[allow(unused_macros)]
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(),
            )+
        )
    }}
}

#[allow(unused_macros)]
macro_rules! readvec {
    ( $t:ty ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        let mut result = Vec::new();
        for elem in input {
            result.push(elem.parse::<$t>().unwrap());
        }
        result
    }}
}

fn main() {
    let a = readvec!(i32);
    let b = a.iter().fold(0,|x,y| x+y);
    println!("{}",if b%a.len() as i32 == 0 { b/a.len() as i32 } else { -1 });
}


fn main() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let size = s.split_whitespace().map(|x| x.parse::<i32>().unwrap()).collect::<Vec<i32>>();
    let mut b = false;
    let mut c = -1;
    for i  in 0..=100 {
        if size.iter().map(|x| x-i).sum::<i32>() == 0 {
           b = true;
           c = i;
           break;
        }
    }
    println!("{}",c );
}


// {{{ 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 s: i32 = R!(i32, ...).into_iter().sum();
    println!("{}", if s % 5 == 0 { s / 5 } else { -1 });
}


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 next_n<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next::<T>()).collect()
    }

}

fn _main() {
    let mut scan = Scan::new();
    let bets: Vec<usize> = scan.next_n(5);
    let total: usize = bets.iter().sum();
    let (valid, result) = (total%5==0, total/5);
    if valid {
        println!("{}", result);
    } else {
        println!("-1");
    }
}

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


use std::io::stdin;
fn main() {
    let (mut h, m) = parse();
    let e = h;
    while reverse_number(h) > 59 || (reverse_number(h) <= m && h == e) {
        h += 1;
    }
    print_it(h, reverse_number(h));
}

fn parse() -> (usize, usize) {
    let mut entry = String::new();
    let mut hours = String::new();
    let mut minutes = String::new();
    let mut b = false;
    stdin().read_line(&mut entry).unwrap();

    for i in entry.trim().chars() {
        if i == ':' {
            b = true;
        } else if b {
            minutes.push(i);
        } else {
            hours.push(i);
        };
    }
    (hours.parse().unwrap(), minutes.parse().unwrap())
}

fn reverse_number(val: usize) -> usize {
    ((val % 10) * 10) + ((val - (val % 10)) / 10)
}

fn print_it(a: usize, b: usize) {
    let hours: String;
    let minutes: String;

    if a < 10 {
        hours = format!("0{}", a);
    } else {
        hours = format!("{}", a);
    };
    if b < 10 {
        minutes = format!("0{}", b);
    } else {
        minutes = format!("{}", b);
    };
    println!("{}:{}", hours, minutes);
}


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

fn count_bits(n: u64) -> u64 {
    let mut n = n;
    let mut ans = 0;
    while n > 0 {
        ans += 1;
        n >>= 1;
    }
    ans
}

fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) {
    let n: u64 = scan.token();
    let k: u64 = scan.token();
    // Maximize the xor-sum of at most k numbers from 1 to n
    // For any bit pattern that represents a positive number, its negation is always less than the number itself.
    // For example, n = 6 = 110 -> neg(n) = 001
    // n ^ neg(n) = 111
    // The answer is num_bits(n) ones, if k >= 2
    if k == 1 {
        writeln!(out, "{}", n).ok();
    }
    let num_bits = count_bits(n);
    let mut ans = 0u64;
    for i in 0..(num_bits) {
        ans = ans | (1 << i);
    }
    writeln!(out, "{}", ans).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);
}

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

    pub fn tokens<T: str::FromStr>(&mut self) -> Vec<T> {
        assert!(self.buffer.is_empty());
        let mut input = String::new();
        self.reader.read_line(&mut input).expect("Failed read");
        input
            .split_whitespace()
            .map(|x| x.parse().ok().expect("Failed parse"))
            .collect()
    }
}


fn dir(c: char) -> i32 {
    match c {
        'v' => 0,
        '<' => 1,
        '^' => 2,
        '>' => 3,
        _ => panic!("Invalid character"),
    }
}

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

    std::io::stdin().read_line(&mut input).unwrap();

    let mut iter = input.chars();

    let start = iter.next().unwrap();
    iter.next().unwrap();
    let end = iter.next().unwrap();

    let mut input = String::new();
    std::io::stdin().read_line(&mut input).unwrap();

    let mut it = input.split_whitespace().map(|x| x.parse::<i32>().unwrap());

    let n = it.next().unwrap();

    if n % 2 == 0 {
        println!("undefined");
    } else if n % 4 == (dir(end) - dir(start)) % 4 {
        println!("cw");
    } else {
        println!("ccw");
    }
}


use std::io;

fn main() {
	let mut input = String::new();
	io::stdin().read_line(&mut input).unwrap();

	let mut iter = input.split_whitespace();
	let n: u16 = iter.next().unwrap().parse().unwrap();
	let a: u16 = iter.next().unwrap().parse().unwrap();
	let b: u16 = iter.next().unwrap().parse().unwrap();

	let mut max: u16 = (a + b) / n;
	let mut min: u16 = 1;
	let mut prev: u16 = 1;

	loop {
		let cur: u16 = (max - min) / 2 + min;

		if cur == prev {
			break;
		}

		if a / cur + b / cur >= n {
			min = cur;
		} else {
			max = cur;
		}

		prev = cur;
	}

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


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

macro_rules! scan_line {
    ($($ty: ty),*) => {{
        let line = read_line();
        let mut iter = line.split_whitespace();
        ($(iter.next().unwrap().parse::<$ty>().unwrap()),*)
    }}
}

fn main() {
    let (n, a, b) = scan_line!(i32, i32, i32);
    let mut l = 1;
    let mut r = n;
    while r - l > 1 {
        let m = l + (r - l) / 2;
        let ap = a / m;
        let bp = b / (n - m);
        if ap == bp {
            l = m;
            break;
        } else if ap < bp {
            r = m;
        } else {
            l = m;
        }
    }
    println!("{}", std::cmp::min(a / l, b / (n - l)));
}


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 modpow(base: u64, expo: u64, modulo: u64) -> u64 {
    let mut ans = 1;
    let mut base = base;
    let mut expo = expo;
    while expo > 0 {
        if expo % 2 != 0 {
            ans *= base;
        }
        base = (base * base) % modulo;
        expo /= 2;
    }
    ans
}

fn is_primitive(x: u64, p: u64) -> bool {
    for i in 1..p - 1 {
        if modpow(x, i, p) == 1 {
            return false;
        }
    }
    modpow(x, p - 1, p) == 1
}

fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) {
    let p: u64 = scan.token();
    let mut ans = 0;
    for x in 1..p {
        if is_primitive(x, p) {
            ans += 1;
        }
    }
    writeln!(out, "{}", ans).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);
}


use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let mut splits = input.split_whitespace();
    let _n = splits.next().unwrap().parse::<i32>().unwrap();
    let k = splits.next().unwrap().parse().unwrap();

    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let a_k = input.split_whitespace().by_ref()
        .nth(k).unwrap().parse::<i32>().unwrap();
    let c = input.split_whitespace().by_ref()
        .map(|e| e.parse::<i32>().unwrap())
        .filter(|&elem| elem > 0 && elem >= a_k)
        .count();
    println!("{:?}", c);
}


use std::io;

fn main() {
    let mut fi = String::new();
    io::stdin().read_line(&mut fi).unwrap();

    let mut si = String::new();
    io::stdin().read_line(&mut si).unwrap();

    let mut nk = fi.trim().split(" ");
    let _n = nk.next().unwrap().parse::<u32>().unwrap();
    let k = nk.next().unwrap().parse::<u32>().unwrap();

    let places = si.trim().split(" ").into_iter().
        map(|d| d.parse::<u32>().unwrap()).collect::<Vec<u32>>();

    let low = places[k as usize];
    let accepted = places.iter().filter(|d| d > &&0 && d >= &&low).
        map(|d| d.clone()).collect::<Vec<u32>>();
    println!("{}", accepted.len());
}


//use std::str::FromStr;

use std::str::FromStr;

#[cfg(test)]
mod tests {
    use crate::quest;

    #[test]
    fn test1() {
            assert_eq!(quest(2,2,1,1),2)
    }
    #[test]
    fn test2() {
        assert_eq!(quest(4,4,2,1),3)
    }
    #[test]
    fn test3() {
        assert_eq!(quest(6,10,4,2),6)
    }

}

#[inline]
pub fn input_in_two_var<T: FromStr>() -> (T, T)
where T: Copy,
{
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    let numbers: Vec<T> = line.split_whitespace().filter_map(
        |s| s.parse().ok()
    )
        .collect();
    (*numbers.get(0).unwrap(),*numbers.get(1).unwrap())
}

fn main()  {
    let (_n,k) = input_in_two_var::<i8>();
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    let numbers: Vec<i64> = line.split_whitespace().filter_map(
        |s| s.parse().ok()
    )
        .collect();
    let mut count: i64 = 0;
    let max: i64 =  *numbers.get(k as usize).unwrap();
    if max >0 {
        for i in numbers {
            if i >= max {
                count += 1;
            }
        }
    }
    println!("{}",count)
}


macro_rules! input {
    ($var:ident) => {
        let mut $var = String::new();
        std::io::stdin().read_line(&mut $var).unwrap();
    };
    ($var:ident, $type: ty) => {
        let mut temp = String::new();
        #[allow(unused_mut)]
        let mut $var : $type;
        std::io::stdin().read_line(&mut temp).unwrap();
        $var = temp.trim().parse::<$type>().unwrap();
    };
}

#[allow(dead_code)]
fn input(var: &mut String) {
    var.clear();
    std::io::stdin().read_line(var).unwrap();
}

fn main() {
    input!(problems, i32);
    let mut opinions = String::new();
    let mut decided_to_solve = 0;

    for _ in 0..problems {
        input(&mut opinions);
        let points: Vec<&str> = opinions.split(' ').collect();
        let sum: i32 = points.iter()
            .map( |c|
                c.trim().parse::<i32>().unwrap()
            )
            .sum();
        if sum > 1 {
            decided_to_solve += 1;
        }
    }

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


use std::io;

fn main() {
  let mut a_str = String::new();
  io::stdin().read_line(&mut a_str).expect("read error");
  let _vec = a_str.split_whitespace()
    .map(|x| x.parse::<i32>().expect("parse error"))
    .collect::<Vec<i32>>();

  let _n = _vec[0];
  let _k = _vec[1] as usize;

  let mut b_str = String::new();
  io::stdin().read_line(&mut b_str).expect("READ ERROR");
  let _vec2 = b_str.split_whitespace()
    .map(|x| x.parse::<i32>().expect("parse error!"))
    .collect::<Vec<i32>>();

  let score_last_hope = _vec2[_k];

  let mut count = 0;
  for num in &_vec2 {
    if (*num <= 0) {
      break;
    }
    if *num >= score_last_hope {
      count += 1;
    } else {
      break;
    }
  }

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


use std::io::stdin;
#[derive(Default)]
struct Scanner {
    buffer: Vec<String>,
}
impl Scanner {
    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();
            stdin().read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let mut scan = Scanner::default();

    let n: u32 = scan.next();
    let k: usize = scan.next();

    let scores: Vec<u32> = (0..n).map(|_| scan.next()).collect();

    let mut index = scores.len();
    for (idx, score) in (&scores[k + 1..]).iter().enumerate() {
        if *score < scores[k] {
            index = idx + k + 1;
            break;
        }
    }

    println!("{:?}", &scores[..index as usize].iter().filter(|score| **score != 0).count())
}


use std::io;

macro_rules! parse_line {
    ($($t: ty),+) => ({
        let mut a_str = String::new();
        io::stdin().read_line(&mut a_str).expect("read error");
        let mut a_iter = a_str.split_whitespace();
        (
            $(
            a_iter.next().unwrap().parse::<$t>().expect("parse error"),
            )+
        )
    })
}

fn parse_array() -> Vec<u64> {
    let mut a_str = String::new();
    io::stdin().read_line(&mut a_str).expect("read error");
    a_str
        .split_whitespace()
        .map(|x| x.parse::<u64>().expect("parse error"))
        .collect()
}

fn main() {
    let (_, k) = parse_line!(usize, usize);
    let arr = parse_array();
    let x = arr[k];
    println!("{}", arr.iter().take_while(|n| **n >= x && x > 0).count());
}


fn read()->Vec<i32>{
    let mut line=String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    line.split_whitespace().map(|x|x.parse::<i32>().unwrap()).collect()
}
fn main(){
    let options=read();
    let n=options[0] as usize;
    let k=options[1] as usize;
    let vec=read();
    let mut d=0;
    for c in 0..n{
        if vec[c]>=vec[k] && vec[c]>0{d+=1}
    }
    println!("{}",d);
}


fn main() {
    let k = (read_numbers())[1];

    let scores    = read_numbers();
    let limit     = scores[k];
    let mut count = 0;

    for score in scores {
        if score >= limit && score > 0 {
            count += 1;
        } else {
            break;
        }
    }

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

fn read_numbers() -> std::vec::Vec<usize> {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).unwrap();

    buffer.trim().split_whitespace().map(|x| x.parse::<usize>().unwrap()).collect::<std::vec::Vec<usize>>()
}


use std::io;

fn main (){
    let s1 = String::new();
    io::stdin().read_line(&mut s1).expect("e");

    let mut v1 :Vec<i32> = s1.trim()
        .split(" ")
        .map(|x|{x.parse::<i32>().expect("e")})
        .collect();

    let mut s2 = String::new();
    io::stdin().read_line(&mut s2).expect("e");
    let mut v2 :Vec<i32> = s2.trim()
        .split(" ")
        .map(|x|{x.parse::<i32>().expect("e")})
        .filter(|x|{x>&v1[1]})
        .collect();

    println!("{}",v2.iter().count());

}


use std::io;

fn main() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).expect("e");

    let mut v : Vec<i32> = s.trim()
        .split(" ")
        .map(|x| {x.parse::<i32>().expect("e")})
        .collect();

    let mut s1 = String::new();
    io::stdin().read_line(&mut s1).expect("e");

    let mut v1 : Vec<i32> = s1.trim()
        .split(" ")
        .map(|x| {x.parse::<i32>().expect("e")})
        .collect();

    let mut res =0;
    if v1[0] == 0{
        println!("0");
    }else{
        let mut k = v1[v[1]as usize];

        for (ix,i) in v1.iter().enumerate() {
            if (k==*i){
               res = ix+1;
            }
        }
    println!("{}",res);
    }
    }


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 main() {
    let stdin = io::stdin();
    let mut scan = Scanner::new(stdin.lock());

    let n = scan.token::<u8>();
    let k = scan.token::<u8>();

    let mut a: Vec<u8> = Vec::new();

    for _i in 0..n {
        let point = scan.token::<u8>();
        a.push(point);
    }

    let mut i: usize = 0;
    let mut needle: u8 = 0;

    loop {
        if a[i] < 1 {
            println!("{}", i);
            break;
        } else {
            if needle > a[i] {
                println!("{}", i);
                break;
            }
            if i == (k as usize - 1) {
                needle = a[i];
            }
        }
        i += 1;
    }
}


use std::io;

fn main() -> std::io::Result<()> {
    let stdin = io::stdin();
    let mut parameters = String::new();
    let mut scores = String::new();
    stdin.read_line(&mut parameters)?;
    stdin.read_line(&mut scores)?;
    let pos = parameters.split(" ").next().unwrap().parse::<usize>().unwrap();
    let scores =
        scores
            .split_ascii_whitespace()
            .map(|x| x.parse::<i32>().unwrap())
            .collect::<Vec<i32>>();

    print!("{}", n_moves_on(scores, pos));
    Ok(())
}
fn n_moves_on(scores: Vec<i32>, pos: usize) -> usize {
    let nth_score = scores[pos];
    scores.iter().filter(|&&x| x >= nth_score && x > 0).count()
}


fn input() -> String {
    let mut input = String::new();
    std::io::stdin()
        .read_line(&mut input)
        .ok()
        .expect("Read Error");

    input.trim().to_string()
}

fn main() {
    let n_k = input().split_ascii_whitespace().map(|x| { x.parse::<usize>().unwrap_or(0) }).collect::<Vec<_>>();
    let (_, k) = (n_k[0], n_k[1]);
    let mut scores = input().split_ascii_whitespace().map(|x| { x.parse::<u8>().unwrap_or(0) }).collect::<Vec<u8>>();
    scores.sort_by(|a, b| b.cmp(a));

    let mut participants = 0;
    for score in &scores {
        if score >= &scores[k] && score > &0 {
            participants += 1;
        } else { break; }
    }

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


#[allow(dead_code)]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}
#[allow(dead_code)]
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}
#[allow(dead_code)]
fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}
#[allow(dead_code)]
fn yn(result: bool) {
    if result {
        println!("Yes");
    } else {
        println!("No");
    }
}

fn main() {
    let v = read_vec::<usize>();
    let _n = v[0];
    let k = v[1];

    let av = read_vec::<u32>();
    let ak = av[k];
    let ans = av.into_iter().filter(|&ai| ai > 0 && ai >= ak).count();
    println!("{}", ans);
}


use std::io;

fn main() {
  	let mut input = String::new();
    let stdin = io::stdin();
  	stdin.read_line(&mut input).unwrap();
  	let n = input.trim().parse::<usize>().unwrap();
	let mut v: Vec<i32> = Vec::new();
input.clear();
  	stdin.read_line(&mut input)
          .expect("correct input");
	for u in input.trim().split(' ') {
          let cur_txt = u.trim();
          if cur_txt.len() > 0 {
            let cur_num: i32 = cur_txt.parse().unwrap();
            v.push(cur_num);
        }
    }
    if n == 1 {
    	if v[0] == 15 {
			println!("DOWN");
		} else if v[0] == 0 {
			println!("UP");
		} else {
			println!("-1");
		}
    } else {
    	if v[n-1] == 15 {
			println!("DOWN");
		} else if v[n-2] == 0 {
			println!("UP");
		} else if v[n-2] > v[n-1] {
			println!("DOWN");
		} else {
			println!("UP");
		}
    }
}


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 next_n<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next::<T>()).collect()
    }
}

fn _main() {
    let mut scan = Scan::new();
    let n: usize = scan.next();
    let arr: Vec<usize> = scan.next_n(n);
    if arr.len() == 1 {
        if arr[0] == 0 {
            println!("UP");
        } else if arr[0] == 15 {
            println!("DOWN");
        } else {
            println!("-1");
        }
        return;
    }
    let last = arr[arr.len() - 1];
    let last2 = arr[arr.len() - 2];
    if last > last2 || last == 0 && last2 == 1 {
        println!("UP");
    } else {
        println!("DOWN");
    }
}

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


use std::io;

fn main()
{
	let mut s = String::new();
	let mut n = String::new();
	io::stdin().read_line(&mut n).unwrap();
	let n = n.trim().parse::<u8>().unwrap();
	io::stdin().read_line(&mut s).unwrap();
	s = s.trim().to_string();
	let val: Vec<i8> = s.split(" ").map(|x: &str| x.parse::<i8>().unwrap()).collect();

	if n < 2 {
		print!("{}", -1);
		return;
	}
	if let Ok(res) = match val[val.len()-1] {
		0 => Ok("UP"),
		15 => Ok("DOWN"),
		_ => match val[val.len()-1] - val[val.len()-2] {
			1 => Ok("UP"),
			-1 => Ok("DOWN"),
			_ => Err("invalid input"),
		}
	} {
		print!("{}", res);
	}
	else {
		print!("{}", "invalid input");
	}

}


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

fn main() {
    let mut buffer = String::new();
    let stdin = io::stdin();
    let mut handle = stdin.lock();
    handle.read_to_string(&mut buffer).unwrap();

    let arr : Vec<_> = buffer.split_whitespace().map(|x| x.parse::<u64>().unwrap() ).collect();
    let n = arr[0];
    let mut d = 0;
    let mut h = n;
    while h > 0 {
        d += 1;
        h = h / 10;
    }
    use std::cmp;
    let mut a = 0;
    'outer: for i in 0..d {
        // println!("{}",a);
        let mut r = 0;
        for j in 0..10 {
            let y = j * 10u64.pow(i);
            if a + y <= n {
                r = cmp::max(a + y, r);
                // println!("{}",r);
            }
            a = r;
        }
    }
    let mut b = n - a;
    // println!("{} {}", a, b);
    let mut ans = 0;
    while a > 0 {
        ans += a % 10;
        a = a / 10;
    }
    while b > 0 {
        ans += b % 10;
        b = b / 10;
    }
    println!("{}", ans);
}


use std::io::{stdin, stdout, BufWriter, Write};

#[derive(Default)]
struct Scanner {
    buffer: Vec<String>,
}
impl Scanner {
    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();
            stdin().read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let mut scan = Scanner::default();

    let info: Vec<i32> = (0..2).map(|_| scan.next()).collect();
    let mut cost = 0;
    let mut tank = 0;

    for i in 0..info[0] - 1 {
        if tank < (info[0] - 1 - i) {
            cost += (info[1] - tank) * (i + 1);
            tank = info[1];
        }
        tank -= 1;
    }

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


#[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 {
    (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")
    };
}

const LINF: i64 = 1 << 58;

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($format:expr) => (write!(out,$format).unwrap());
        ($format:expr, $($args:expr),+) => (write!(out,$format,$($args),*).unwrap())
    }
    input!{
        n: usize,
        a: [[i32; n]; n],
    }
    let ni = n as i32;
    let mut pos = vec![0; n * n];
    for i in 0 .. n {
        for j in 0 .. n {
            pos[a[i][j] as usize - 1] = i * n + j;
        }
    }
    let mut kn = vec![vec![LINF >> 32; n * n]; n * n];
    let mut rk = vec![vec![LINF >> 32; n * n]; n * n];
    let mut bs = vec![vec![LINF >> 32; n * n]; n * n];
    for i in 0 .. n {
        for j in 0 .. n {
            for &(dx, dy)
                in &[(-2, -1), (-2, 1), (2, -1), (2, 1),
                     (1, 2), (-1, 2), (1, -2), (-1, -2)] {
                    let nx = i as i32 + dx;
                    let ny = j as i32 + dy;
                    if nx < 0 || nx >= ni || ny < 0 || ny >= ni { continue; }
                    let v = (nx * ni + ny) as usize;
                    kn[i * n + j][v] = 1;
                }
            for dx in -ni .. ni {
                let dy = dx;
                let nx = i as i32 + dx;
                let ny = j as i32 + dy;
                if nx < 0 || nx >= ni || ny < 0 || ny >= ni { continue; }
                let v = (nx * ni + ny) as usize;
                bs[i * n + j][v] = 1;
                let dy = -dx;
                let nx = i as i32 + dx;
                let ny = j as i32 + dy;
                if nx < 0 || nx >= ni || ny < 0 || ny >= ni { continue; }
                let v = (nx * ni + ny) as usize;
                bs[i * n + j][v] = 1;
            }
            for u in 0 .. n {
                rk[i * n + j][u * n + j] = 1;
                rk[i * n + j][i * n + u] = 1;
            }
            kn[i * n + j][i * n + j] = 0;
            rk[i * n + j][i * n + j] = 0;
            bs[i * n + j][i * n + j] = 0;
        }
    }
    let mut dist = vec![vec![LINF; 3 * n * n]; 3 * n * n];
    for i in 0 .. n * n {
        for j in 0 .. n * n {
            dist[i][j] = kn[i][j] << 32;
            dist[n * n + i][n * n + j] = rk[i][j] << 32;
            dist[2 * n * n + i][2 * n * n + j] = bs[i][j] << 32;
        }
        for j in 0 .. 3 {
            for k in 0 .. 3 {
                if j != k {
                    dist[j * n * n + i][k * n * n + i] = 1 << 32 | 1;
                }
            }
        }
    }
    for k in 0 .. 3 * n * n {
        for i in 0 .. 3 * n * n {
            for j in 0 .. 3 * n * n {
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
            }
        }
    }
    // eprintln!("dist = {:?}", dist);
    let mut dp = vec![[LINF; 3]; n * n];
    dp[0] = [0; 3];
    for i in 0 .. n * n - 1 {
        let src = pos[i];
        let dst = pos[i + 1];
        for j in 0 .. 3 {
            for k in 0 .. 3 {
                let cost: i64 = dist[j * n * n + src][k * n * n + dst];
                //eprintln!("{} -> {}", j * n * n + src, k * n * n + dst);
                //eprintln!("src = {}, dst = {}, cost = {}", src, dst, cost);
                dp[i + 1][k] = min(dp[i + 1][k], cost + dp[i][j]);
            }
        }
        //eprintln!("dp[{}] = {:?}", i + 1, dp[i + 1]);
    }
    let mut mi = LINF;
    for i in 0 .. 3 { mi = min(mi, dp[n * n - 1][i]); }
    puts!("{} {}\n", mi >> 32, mi as i32);
}

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


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" ) } ;}
trait Monoid {
    fn id() -> Self;
    fn f(a: Self, b: Self) -> Self;
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum MaxInt {
    Minimal,
    Val(i64),
}
impl std::ops::Mul for MaxInt {
    type Output = Self;
    fn mul(self, other: Self) -> Self {
        if self > other {
            self
        } else {
            other
        }
    }
}
impl MaxInt {
    fn unwrap(self) -> i64 {
        if let Self::Val(x) = self {
            x
        } else {
            panic!();
        }
    }
    fn map<F>(self, f: F) -> Self
    where
        F: Fn(i64) -> i64,
    {
        if let Self::Val(x) = self {
            Self::Val(f(x))
        } else {
            Self::Minimal
        }
    }
}
impl Monoid for MaxInt {
    fn id() -> Self {
        MaxInt::Minimal
    }
    fn f(a: Self, b: Self) -> Self {
        a * b
    }
}
use MaxInt::*;

fn main() {
    input! {
        n: usize,
        k: usize,
        s: String,
        t: String,
    }
    let s = s.chars().map(|c| c as u8).collect::<Vec<_>>();
    let t = t.chars().map(|c| c as u8).collect::<Vec<_>>();
    if t[0] == t[1] {
        let mut ans = 0;
        let mut c = 0;
        let mut k = k;
        for i in 0..n {
            if k != 0 && s[i] != t[0] {
                ans += c;
                c += 1;
                k -= 1;
            }
            if s[i] == t[0] {
                ans += c;
                c += 1;
            }
        }
        println!("{}", ans);
        return;
    }
    if k == 0 {
        let mut ans = 0;
        let mut c = 0;
        for i in 0..n {
            if s[i] == t[0] {
                c += 1;
            }
            if s[i] == t[1] {
                ans += c;
            }
        }
        println!("{}", ans);
        return;
    }

    let mut dp = vec![vec![vec![Minimal; n + 1]; k + 1]; n + 1];
    dp[0][0][0] = Val(0);
    for i in 0..n {
        for k in 0..k {
            for c in 0..=i {
                if s[i] == t[0] {
                    dp[i + 1][k][c + 1] = dp[i + 1][k][c + 1] * dp[i][k][c];
                } else {
                    dp[i + 1][k + 1][c + 1] = dp[i + 1][k + 1][c + 1] * dp[i][k][c];
                }
                if s[i] == t[1] {
                    dp[i + 1][k][c] = dp[i + 1][k][c] * dp[i][k][c].map(|v| v + c as i64);
                } else {
                    dp[i + 1][k + 1][c] = dp[i + 1][k + 1][c] * dp[i][k][c].map(|v| v + c as i64);
                }
                if s[i] != t[0] && s[i] != t[1] {
                    dp[i + 1][k][c] = dp[i + 1][k][c] * dp[i][k][c];
                }
            }
        }
    }
    let mut ans = Minimal;
    for k in 0..=k {
        for c in 0..=n {
            ans = ans * dp[n][k][c];
        }
    }
    println!("{}", ans.unwrap());
}


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" ) } ;}
trait Monoid {
    fn id() -> Self;
    fn f(a: Self, b: Self) -> Self;
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum MaxInt {
    Minimal,
    Val(i64),
}
impl std::ops::Mul for MaxInt {
    type Output = Self;
    fn mul(self, other: Self) -> Self {
        if self > other {
            self
        } else {
            other
        }
    }
}
impl MaxInt {
    fn unwrap(self) -> i64 {
        if let Self::Val(x) = self {
            x
        } else {
            panic!();
        }
    }
    fn map<F>(self, f: F) -> Self
    where
        F: Fn(i64) -> i64,
    {
        if let Self::Val(x) = self {
            Self::Val(f(x))
        } else {
            Self::Minimal
        }
    }
}
impl Monoid for MaxInt {
    fn id() -> Self {
        MaxInt::Minimal
    }
    fn f(a: Self, b: Self) -> Self {
        a * b
    }
}
use MaxInt::*;

fn main() {
    input! {
        n: usize,
        k: usize,
        s: String,
        t: String,
    }
    let s = s.chars().map(|c| c as u8).collect::<Vec<_>>();
    let t = t.chars().map(|c| c as u8).collect::<Vec<_>>();
    if t[0] == t[1] {
        let mut ans = 0;
        let mut c = 0;
        let mut k = k;
        for i in 0..n {
            if k != 0 && s[i] != t[0] {
                ans += c;
                c += 1;
                k -= 1;
            }
            if s[i] == t[0] {
                ans += c;
                c += 1;
            }
        }
        println!("{}", ans);
        return;
    }

    let mut dp = vec![vec![vec![Minimal; n + 1]; k + 2]; n + 1];
    dp[0][0][0] = Val(0);
    for i in 0..n {
        for k in 0..k {
            for c in 0..=i {
                if s[i] == t[0] {
                    dp[i + 1][k][c + 1] = dp[i + 1][k][c + 1] * dp[i][k][c];
                } else {
                    dp[i + 1][k + 1][c + 1] = dp[i + 1][k + 1][c + 1] * dp[i][k][c];
                }
                if s[i] == t[1] {
                    dp[i + 1][k][c] = dp[i + 1][k][c] * dp[i][k][c].map(|v| v + c as i64);
                } else {
                    dp[i + 1][k + 1][c] = dp[i + 1][k + 1][c] * dp[i][k][c].map(|v| v + c as i64);
                }
                if s[i] != t[0] && s[i] != t[1] {
                    dp[i + 1][k][c] = dp[i + 1][k][c] * dp[i][k][c];
                }
            }
        }
    }
    let mut ans = Minimal;
    for k in 0..=k {
        for c in 0..=n {
            ans = ans * dp[n][k][c];
        }
    }
    println!("{}", ans.unwrap());
}