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

macro_rules! debug(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

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

impl Scanner {

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

   fn process(&mut self) -> String {
      if self.buffer.len() == 0 {
         let mut input = String::new();
         std::io::stdin().read_line(&mut input).ok();
         for word in input.split_whitespace() {
            self.buffer.push_back(word.to_string())
         }
      }

      self.buffer.pop_front().unwrap()
   }

   fn next<T : std::str::FromStr >(&mut self) -> T {
      self.process().parse::<T>().ok().unwrap()
   }

   fn next_char(&mut self) -> char {
      self.process().into_bytes()[0] as char
   }
}

fn main() {
   let mut sin = Scanner::new();
   let (m, d) : (usize, i32) = (sin.next(), sin.next());

   let month_days = vec![31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

   let mut days = month_days[m-1];

   let mut columns = 1;
   days -= 7 - d + 1;

   while days > 7 {
      columns += 1;
      days -= 7;
   }

   if days > 0 {
      columns += 1;
   }

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


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

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

    fn next_line(&self) -> String {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("Fail to read");
        line
    }

    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 line = self.next_line();
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }
}

fn sumdigits(x: i64) -> usize {
    let mut result = 0usize;
    let mut tmp = x;
    while tmp > 0 {
        result += (tmp % 10) as usize;
        tmp /= 10;
    }
    result
}

fn _main() {
    let mut scan = Scan::new();
    let a: u32 = scan.next();
    let b: isize = scan.next();
    let c: isize = scan.next();
    let mut result: Vec<i64> = vec![];
    for i in 0usize..=81 {
        let x: i64 = (i.pow(a) as i64) * (b as i64) + (c as i64);
        if x <= 0 {
            continue;
        }
        if x >= 1000000000 {
            break;
        }
        if sumdigits(x) == i {
            result.push(x);
        }
    }
    println!("{}", result.len());
    for &item in &result {
        print!("{} ", item);
    }
    if result.len() != 0 {
        println!();
    }
}

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


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

pub struct Scanner<R> {
    reader: R,
    buffer: Vec<String>,
}

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

    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn digit_sum(x: i64) -> i64 {
    let mut x = x;
    let mut ans = 0;
    while x > 0 {
        ans += x % 10;
        x /= 10;
    }
    ans
}

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

    for s_x in 1i64..=81i64 {
        let x = b * s_x.pow(a) + c;
        if x >= 1000000000 {
            break;
        }
        if digit_sum(x) == s_x {
            ans.push(x.to_string());
        }
    }
    writeln!(out, "{}", ans.len()).ok();
    writeln!(out, "{}", ans.join(" ")).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);
}


#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(dead_code)]

#[allow(unused_macros)]
macro_rules! invec {
    ( $ t : ty ) => {{
        let mut s = String::new();
        match std::io::stdin().read_line(&mut s) {
            Ok(0) => Vec::<$t>::new(),
            Ok(n) => s
                .trim()
                .split_whitespace()
                .map(|s| s.parse::<$t>().unwrap())
                .collect::<Vec<$t>>(),
            Err(_) => Vec::<$t>::new(),
        }
    }};
}

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

#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut 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)*}
    };
    ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

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

    ($next:expr, [$t:tt]) => {
        {
            let len = read_value!($next, usize);
            (0..len).map(|_| read_value!($next, $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")
    };
}

#[allow(unused_macros)]
#[cfg(debug_assertions)]
macro_rules! mydbg {
    //($arg:expr) => (dbg!($arg))
    //($arg:expr) => (println!("{:?}",$arg));
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
      }
}
#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

macro_rules! echo {
    ($($a:expr),*) => {
          $(println!("{}",$a))*
      }
}

use std::cmp::*;
use std::collections::*;
use std::ops::{Add, Div, Mul, Sub};

#[allow(dead_code)]
static INF_I64: i64 = i64::max_value() / 2;
#[allow(dead_code)]
static INF_I32: i32 = i32::max_value() / 2;
#[allow(dead_code)]
static INF_USIZE: usize = usize::max_value() / 2;
#[allow(dead_code)]
static M_O_D: usize = 1000000007;
#[allow(dead_code)]
static PAI: f64 = 3.1415926535897932;

trait IteratorExt: Iterator {
    fn toVec(self) -> Vec<Self::Item>;
}

impl<T: Iterator> IteratorExt for T {
    fn toVec(self) -> Vec<Self::Item> {
        self.collect()
    }
}

trait CharExt {
    fn toNum(&self) -> usize;
    fn toAlphabetIndex(&self) -> usize;
    fn toNumIndex(&self) -> usize;
}
impl CharExt for char {
    fn toNum(&self) -> usize {
        return *self as usize;
    }
    fn toAlphabetIndex(&self) -> usize {
        return self.toNum() - 'a' as usize;
    }
    fn toNumIndex(&self) -> usize {
        return self.toNum() - '0' as usize;
    }
}

trait VectorExt {
    fn joinToString(&self, s: &str) -> String;
}
impl<T: ToString> VectorExt for Vec<T> {
    fn joinToString(&self, s: &str) -> String {
        return self
            .iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(s);
    }
}

trait StringExt {
    fn get_reverse(&self) -> String;
}
impl StringExt for String {
    fn get_reverse(&self) -> String {
        self.chars().rev().collect::<String>()
    }
}

trait UsizeExt {
    fn pow(&self, n: usize) -> usize;
}
impl UsizeExt for usize {
    fn pow(&self, n: usize) -> usize {
        return ((*self as u64).pow(n as u32)) as usize;
    }
}

fn main() {
    let (a, b, c) = get!(i64, i64, i64);
    let mut k = vec![];
    for i in 0..100 {
        k.push((b * ((i as i64).pow(a as u32)) + c, i));
    }
    let mut ans = vec![];
    for &(d, e) in &k {
        if d <= 0 {
            continue;
        } else if d > 10_i64.pow(9) {
            continue;
        }
        let f = d
            .to_string()
            .chars()
            .map(|x| x as usize - '0' as usize)
            .fold(0, |a, x| a + x);
        if f == e {
            ans.push(d);
        }
    }
    echo!(ans.len());
    echo!(ans.joinToString(" "));
}


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 mut sides: Vec<isize> = scan.next_n(3);
    sides.sort();
    let x = sides[2] - sides[1];
    if sides[0] > x {
        println!("0");
    } else {
        println!("{}", x - sides[0] + 1);
    }
}

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


//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::iter::*;
#[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 sk(&mut self, n: usize) { self.it.nth(n - 1); }
    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

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

    let mut a = input.vi(3);
    a.sort();
    println!("{}", 0.max(a[2] + 1 - a[1] - a[0]));
}


use std::io;
use std::collections::BTreeSet;

fn max(x: &BTreeSet<i32>, y: &BTreeSet<i32>) -> (BTreeSet<i32>, BTreeSet<i32>) {
    let mut r: BTreeSet<i32> = BTreeSet::new();
    let mut rx: BTreeSet<i32> = BTreeSet::new();
    let mut xiter = x.iter();
    let mut yiter = y.iter();
    let mut i: i32 = *(xiter.next().unwrap());
    let mut j: i32 = *(yiter.next().unwrap());
    if i < j {
        while i < j { match xiter.next() {
            Some(x) => i = *x,
            None => { i = -1; break }
        } }
    } else {
        if j < i {
            while j < i { match yiter.next() {
                Some(x) => j = *x,
                None => { j = -1; break }
            } }
        }
    }
    if i != -1 { r.insert(i); }
    if j != -1 { r.insert(j); rx.insert(j); }
    for x in xiter { r.insert(*x); }
    for y in yiter { r.insert(*y); rx.insert(*y); }
    (r, rx)
}

fn main() {
    let mut l = String::new();
    io::stdin().read_line(&mut l).unwrap();
    let x: Vec<i32> = l.trim().split_whitespace().map(|x| x.parse().unwrap()).collect();
    let (_, k) = (x[0], x[1]);
    let mut xs = String::new();
    io::stdin().read_line(&mut xs).unwrap();
    let mut r: BTreeSet<i32> = BTreeSet::new();
    r.insert(-1);
    for x in xs.trim().split('Y') {
        let mut rr: BTreeSet<i32> = BTreeSet::new();
        let mut rc: BTreeSet<i32> = BTreeSet::new();
        rr.insert(-1);
        rc.insert(-1);
        for g in x.split('?') {
            let mut rs: BTreeSet<i32> = BTreeSet::new();
            let gl = g.len() as i32;
            rs.insert(gl);
            let (u, ux) = max(&rr, &rs);
            rr = &u | &(rc.iter().map(|x| x + gl + 1).collect());
            rc = &ux | &(rc.iter().map(|x| x + gl + 1).collect());
        }
        r = max(&r, &rr).0;
    }
    if r.contains(&k) {
        println!("YES");
    } else {
        println!("NO");
    }
}


use std::io;

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

    let a = v[0];
    let b = v[1];
    let c = v[2];
    let n = v[3];

    let sol = n - a - b + c;

    if sol < 1 || c > a || c > b {
        println!("-1");
    } else {
        println!("{}", sol);
    }
}


fn main() {
    let mut input = String::new();
    use std::io::{self, prelude::*};
    io::stdin().read_to_string(&mut input).unwrap();

    let mut it = input.split_whitespace();
    let a: usize = it.next().unwrap().parse().unwrap();
    let b: usize = it.next().unwrap().parse().unwrap();
    let c: usize = it.next().unwrap().parse().unwrap();
    let n: usize = it.next().unwrap().parse().unwrap();

    let ans = c <= a &&
        c <= b &&
        a < n &&
        b < n &&
        a + b - c < n;

    if ans {
        println!("{}", n + c - a - b) ;
    } else {
        println!("-1");
    }
}


// 991A
use std::cmp::min;
use std::io;

fn main() {
    let (a, b, c, n): (u32, u32, u32, u32) = read_two(&io::stdin());
    if a + b - c + 1 > n || c > min(a, b) {
        println!("{}", -1);
    } else {
        println!("{}", n - (a + b - c));
    }
}

fn read_two<T>(stdin: &io::Stdin) -> (T, T, 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(),
        iter.next().unwrap(),
        iter.next().unwrap(),
    )
}


#[allow(unused_imports)]
use std::io;
use std::cmp::{min, max};
use std::mem;
use std::str::FromStr;
use std::cmp::Ordering;
use std::collections::BinaryHeap;

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

    pub fn next_vec<T: ::std::str::FromStr>(&mut self, len: usize) -> Vec<T>
        where
            T::Err: ::std::fmt::Debug,
    {
        (0..len).map(|_| self.next::<T>()).collect::<Vec<T>>()
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
struct ReverseInt(i64);

impl Ord for ReverseInt {
    fn cmp(&self, other: &ReverseInt) -> Ordering {
        other.0.cmp(&self.0)
    }
}

impl PartialOrd for ReverseInt {
    fn partial_cmp(&self, other: &ReverseInt) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

fn main1() {
    let stdin = io::stdin();
    let mut input = Scanner::new(stdin.lock());
    let n: usize = input.next();
    let mut v: Vec<i64> = input.next_vec(n);
    v.sort();
    println!("{}", v[n / 2]);
}

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


use std::io;

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

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

    let res = input
        .trim()
        .split(' ')
        .map(|x| x.parse::<i32>())
        .map(|x| x.expect("expected number"))
        .fold(0i32, |sum, x| sum + x);

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


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

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

    fn next_line(&self) -> String {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("Fail to read");
        line
    }

    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 line = self.next_line();
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }
}

static BIG: i64 = 1e9 as i64 + 7;
fn _main() {
    let mut scan = Scan::new();
    let mut x: i64 = scan.next();
    let mut y: i64 = scan.next();
    let mut n: i64 = scan.next();
    let mut i = 2i64;
    n = n % 6;
    // I think it would be better to precompute an
    // array with the 6 different possible values
    while i < n + 6 {
        let tmp = y;
        y = (y - x + BIG) % BIG;
        x = tmp;
        i += 1;
    }
    println!("{}", (y + BIG) % BIG);
}

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_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);

    let x = Field::new(input.i());
    let y = Field::new(input.i());
    let n = input.u();
    let mut a = vec![x,y];
    for i in 2..6 {
        let res = a[i-1] - a[i-2];
        a.push(res);
    }
    println!("{}", a[(n - 1) % 6]);
}


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

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

    stdin.lock().read_line(&mut input).unwrap();

    let seq = input.trim().as_bytes();

    let n = seq.len();
    let mut largest = seq.to_vec();
    for i in 1..2usize.pow(n as u32) {
        let mut subseq = Vec::with_capacity(n);
        for k in 0..n {
            if i >> k & 1 == 1 {
                subseq.push(seq[k])
            }
        }
        if !is_palindrome(&subseq) {
            continue;
        }
        if is_lexicographically_larger(&subseq, &largest) {
            largest = subseq;
        }
    }
    println!("{}", String::from_utf8_lossy(&largest));
}

fn is_palindrome(seq: &[u8]) -> bool{
    for i in 0..seq.len()/2 {
        if seq[i] != seq[seq.len()-i-1] {
            return false;
        }
    }

    true
}

fn is_lexicographically_larger(a: &[u8], b: &[u8]) -> bool {
    let mut i = 0;
    let mut same = true;

    while i < a.len() && i < b.len() {
        if same {
            if a[i] != b[i] {
                same = false;
            }
        }

        if !same {
            if a[i] <= b[i] {
                return false;
            }
        }
        i += 1;
    }
    true
}


#![allow(unused_imports)]
use std::collections::{HashSet, HashMap};
use std::cmp::{min,max};
use std::io;
use std::str;

struct Scanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: str::SplitWhitespace<'static>,
}
impl<R: io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        Self { reader, buf_str: vec![], buf_iter: "".split_whitespace() }
    }
    fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            // If we have another token in this line
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse"); // calls parse::<T>() on the current token and returns it.
            }

            // If we do not have another token in the line then
            // we should go to the next line.
            self.buf_str.clear(); // empty out the buffer that holds the current line
            self.reader.read_until(b'\n', &mut self.buf_str).expect("Failed read"); // read a new line into the buffer

            // create an iterator over the white space delimited strings of the current line
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str); // makes a string from utf8 characters in the current line
                std::mem::transmute(slice.split_whitespace()) // transmutes the memory in place
            }
        }
    }
}

fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) {
    let n = scan.token::<u32>();
    let mut top = 0;
    let mut bottom = 0;
    let mut flippable = false;
    for _ in 0..n {
        let t = scan.token::<u32>();
        let b = scan.token::<u32>();
        if t % 2 != b % 2 { flippable = true; }
        top += t;
        bottom += b;
    }
    let ans = {
        if top % 2 != 0 && bottom % 2 != 0 && flippable {1}
        else if top % 2 == 0 && bottom % 2 == 0 { 0 }
        else { -1 }
    };
    writeln!(out, "{}", ans);
}

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


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

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

    fn next_line(&self) -> String {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("Fail to read");
        line
    }

    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 line = self.next_line();
            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 find(src: u64, num: u64, n4: usize, n7: usize, result: &mut u64) {
    if num > 10000000000 {
        return;
    }
    if n4 == n7 && num >= src && (num - src) < (*result - src) {
        *result = num;
    }
    find(src, num * 10 + 4, n4 + 1, n7, result);
    find(src, num * 10 + 7, n4, n7 + 1, result);
}

fn _main() {
    let mut scan = Scan::new();
    let n: u64 = scan.next();
    let mut result = std::u64::MAX;
    find(n, 0, 0, 0, &mut result);
    println!("{}", 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_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

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

    l!(n,m = input.i());
    let sol = if n == 1 {
        1
    } else if m - 1 >= n - m {
        m - 1
    } else {
        m + 1
    };
    println!("{}", sol);
}


use std::io;

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

fn read_line_vec() -> Vec<u64> {
    return read_line().split(' ')
        .map(|s| s.parse().unwrap())
        .collect();
}

fn read_line_pair() -> (u64, u64) {
    let vec = read_line_vec();
    return (vec[0], vec[1]);
}

fn get_bp(n: u64, m: u64) -> u64 {
    if n == 1 {
        return 1;
    }
    assert!(m > 0);
    let left = m - 1;
    let right = n - m;

    if left == right {
        return left;
    }
    if left < right {
        return m + 1;
    }
    return left;
}

fn main() {
    let (n, m) = read_line_pair();
    let res = get_bp(n, m);

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


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

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

    fn next_line(&self) -> String {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("Fail to read");
        line
    }

    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 line = self.next_line();
            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);
    let n100 = arr.iter().filter(|x| **x == 100).count();
    let n200 = arr.len() - n100;
    let result = n100 % 2 == 0 && n200 % 2 == 0 || n100 >= 2 && n100 % 2 == 0;
    println!("{}", if result { "YES" } else { "NO" });
}

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


#![allow(unused_imports)]
use std::io::{self, BufWriter, Write};
use std::str::{self, SplitAsciiWhitespace};
use std::cmp::Ordering::{*};

// I have no idea what I'm doing

use std::f64::consts::{PI};

fn main() -> Result<(), io::Error> {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = UnsafeScanner::new(stdin.lock());
    let mut out = BufWriter::new(stdout.lock());

    let n: i64 = scan.token();

    if n == 0 {
        return writeln!(out, "1");
    }

    let is_in = |i, j| i*i + j*j <= n*n;
    // Uncomment for a cool circle in your screen
    // for i in -n..=n {
    //     for j in -n..=n {
    //         write!(out, "{}", if is_in(i.abs(), j.abs()) { '+' }
    //                           else { '-' })?;
    //         write!(out, " ")?;
    //     }
    //     writeln!(out)?;
    // }

    let mut ans = 0;
    let mut y = n;
    for x in 0..=n {
        if is_in(x, y) {
            ans += 1;
        }
        while !is_in(x, y) {
            y -= 1;
            ans += 1;
        }
    }

    writeln!(out, "{}", (ans - 1) * 4)?;

    Ok(())
}

///////////////////////////////////////////////////////////////////////////////////////////////////

/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs
/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts
/// **REQUIRES** Rust 1.34 or higher
pub struct UnsafeScanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: SplitAsciiWhitespace<'static>,
}

impl<R: io::BufRead> UnsafeScanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buf_str: vec![],
            buf_iter: "".split_ascii_whitespace(),
        }
    }

    /// This function should be marked unsafe, but noone has time for that in a
    /// programming contest. Use at your own risk!
    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader
                .read_until(b'\n', &mut self.buf_str)
                .expect("Failed read");
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_ascii_whitespace())
            }
        }
    }

    pub fn pair<T: str::FromStr>(&mut self) -> (T, T) {
        (self.token(), self.token())
    }
}


// https://codeforces.com/contest/1293/problem/F
//
#![allow(unused_imports)]
use std::io::*;
use std::io::Write;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

// Input macros.
// Original by tanakh: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
#[allow(unused_macros)]
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)*}
    };
}

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

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

#[allow(unused_macros)]
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, [ next / $t:tt ]) => {
        {
            let len = read_value!($iter, usize);
            (0..len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
        }
    };

    ($iter:expr, switch) => {
        {
            let ty = read_value!($iter, i32);
            if ty == 1 {
                vec![ty, read_value!($iter, i32), read_value!($iter, i32)]
            } else if ty == 2 {
                vec![ty, read_value!($iter, i32)]
            } else {
                vec![ty, read_value!($iter, i32)]
            }
        }
    };

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

#[allow(unused_macros)]
macro_rules! read_line {
    ($t:tt) => {
        {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            s.trim_right().parse::<$t>().unwrap()
        }
    }
}

#[allow(unused_macros)]
macro_rules! dvec {
    ($t:expr ; $len:expr) => {
        vec![$t; $len]
    };

    ($t:expr ; $len:expr, $($rest:expr),*) => {
        vec![dvec!($t; $($rest),*); $len]
    };
}

#[allow(unused_macros)]
macro_rules! ifv {
    ($t:expr, $a:expr, $b: expr) => {
        if $t { $a } else { $b }
    }
}

#[allow(unused_macros)]
macro_rules! fill {
    ($t:expr, $v:expr) => {
        for i in 0..$t.len() {
            $t[i] = $v;
        }
    };
}

#[allow(unused_macros)]
macro_rules! join {
    ($t:expr, $glue:expr) => {
        $t.into_iter().map(|w| w.to_string()).collect::<Vec<_>>().join($glue)
    };
}

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

// ===

fn generate_primes(upto: usize) -> (Vec<i64>, Vec<bool>) {
    let mut is_prime = vec![true; upto+1];
    is_prime[0] = false;
    is_prime[1] = false;
    for i in 2..upto+1 {
        if is_prime[i] {
            let mut ii = i * i;
            while ii <= upto {
                is_prime[ii] = false;
                ii += i;
            }
        }
    }

    let mut primes = vec![];
    for i in 0..upto+1 {
        if is_prime[i] {
            primes.push(i as i64);
        }
    }
    (primes, is_prime)
}
//===

struct Graph {
    graph: Vec<Vec<(usize, i64)>>,
    vec: Vec<i64>,
    edges: Vec<(usize, usize, i64)>,
    mark: Vec<i64>,
    dcost: Vec<i64>,
}

impl Graph {
    fn generate_next(&mut self, cnt: i64) -> usize {
        self.vec.push(cnt);
        self.vec.len() - 1
    }
    fn add_edge(&mut self, u: usize, v: usize, len: i64) {
        self.edges.push((u, v, len));
    }
}

fn dfs(l: usize, r: usize, depth: usize, parent: usize, table: &Vec<(Vec<i64>, usize, i64)>, graph: &mut Graph) {
    if l == r {
        if table[l].1 >= 2 {
            let nid = graph.generate_next(table[l].2);
            let mut d = 0;

            let pn = table[0].0.len();
            for i in depth..pn {
                d += table[l].0[i];
            }
            graph.add_edge(parent, nid, d);
        }
        return;
    }

    if table[l].0[depth] == table[r].0[depth] {
        if table[l].0[depth] == 0 {
            dfs(l, r, depth+1, parent, table, graph);
        } else {
            let nid = graph.generate_next(0);
            graph.add_edge(parent, nid, table[l].0[depth]);
            dfs(l, r, depth+1, nid, table, graph);
        }
        return;
    }

    let mut ll = l;
    let mut last_value = 0;
    let mut cparent = parent;
    while ll <= r {
        let mut rr = ll;
        while rr <= r && table[ll].0[depth] == table[rr].0[depth] {
            rr += 1;
        }
        // [ll, rr)
        let add_len = table[ll].0[depth] - last_value;
        assert!(add_len >= 0);
        if add_len == 0 {
            dfs(ll, rr-1, depth+1, parent, table, graph);
        } else {
            let nid = graph.generate_next(0);
            graph.add_edge(cparent, nid, add_len);
            dfs(ll, rr-1, depth+1, nid, table, graph);
            cparent = nid;
        }
        last_value = table[ll].0[depth];
        ll = rr;
    }
}

fn dfs2(now: usize, par: usize, g: &mut Graph) -> (i64, i64) {
    let mut total_mark = g.vec[now];
    let mut total_cost = 0;
    for (to, len) in g.graph[now].clone() {
        if to == par {
            continue;
        }
        let (m, c) = dfs2(to, now, g);
        total_mark += m;
        total_cost += c + m * len;
    }
    g.mark[now] = total_mark;
    g.dcost[now] = total_cost;
    (total_mark, total_cost)
}

fn dfs3(now: usize, par: usize, g: &mut Graph) -> i64 {
    let mut best = g.dcost[now];
    for (to, len) in g.graph[now].clone() {
        if to == par {
            continue;
        }
        let mark_back = g.mark[to];
        let dcost_back = g.dcost[to];
        let reduce_cost = g.dcost[to] + g.mark[to] * len;
        let reduce_mark = g.mark[to];

        g.dcost[to] += (g.dcost[now] - reduce_cost) + (g.mark[now] - reduce_mark) * len;
        g.mark[to] += (g.mark[now] - reduce_mark);

        best = min(best, dfs3(to, now, g));

        g.mark[to] = mark_back;
        g.dcost[to] = dcost_back;

    }
    // debug!(now, best);
    best
}

const LIMIT: usize = 5000;

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

    let mut deg = vec![0; LIMIT+1];
    for k in k {
        if k == 0 {
            deg[1] += 1;
        } else {
            deg[k] += 1;
        }
    }
    let (primes, is_prime) = generate_primes(LIMIT+1);

    let mut pn = primes.len();
    let mut vec = vec![];
    // let mut edges = vec![];

    let mut l = LIMIT;
    while l >= 2 {
        let mut lw = l;
        while !is_prime[lw] {
            lw -= 1;
        }

        for num in (lw..=l).rev() {
            let mut ptbl = vec![0; pn];
            for i in 0..pn {
                let mut num = num as i64;
                while num >= primes[i] {
                    ptbl[i] += num / primes[i];
                    num /= primes[i];
                }
            }
            ptbl.reverse();
            vec.push((ptbl, num, deg[num]));
        }
        l = lw-1;
    }
    vec.push((vec![0; pn], 1, deg[1]));
    vec.sort();

    let mut graph = Graph { vec: vec![], edges: vec![], graph: vec![], mark: vec![], dcost: vec![] };
    graph.generate_next(deg[1]);

    dfs(0, vec.len()-1, 0, 0, &vec, &mut graph);

    let vn = graph.vec.len();

    let mut deg = graph.vec.clone();
    let mut g = vec![vec![]; vn];
    for &(u, v, len) in &graph.edges {
        g[u].push((v, len));
        g[v].push((u, len));
    }
    graph.graph = g;
    graph.mark = vec![0; vn];
    graph.dcost = vec![0; vn];

    dfs2(0, vn, &mut graph);

    // debug!(graph.graph);
    // debug!(graph.vec);

    let ans = dfs3(0, vn, &mut graph);
    println!("{}", ans);
}


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Read, Write, BufWriter};
#[allow(dead_code)]
fn getline() -> String {
    let mut ret = String::new();
    std::io::stdin().read_line(&mut ret).ok().unwrap();
    ret
}
fn get_word() -> String {
    let mut stdin = std::io::stdin();
    let mut u8b: [u8; 1] = [0];
    loop {
        let mut buf: Vec<u8> = Vec::with_capacity(16);
        loop {
            let res = stdin.read(&mut u8b);
            if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {
                break;
            } else {
                buf.push(u8b[0]);
            }
        }
        if buf.len() >= 1 {
            let ret = String::from_utf8(buf).unwrap();
            return ret;
        }
    }
}

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

fn 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())
    }
    let s: Vec<i32> = get_word().bytes().map(|x| x as i32 - 48).collect();
    let mut mi = 144;
    for mut v in 0 .. 1000000 {
        let mut t = [0; 6];
        for j in 0 .. 6 {
            t[5 - j] = v % 10;
            v /= 10;
        }
        let mut delta = 0;
        for j in 0 .. 3 { delta += t[j]; }
        for j in 3 .. 6 { delta -= t[j]; }
        let mut diff = 0;
        for j in 0 .. 6 {
            diff += if s[j] != t[j] { 1 } else { 0 };
        }
        if delta == 0 {
            mi = min(mi, diff);
        }
    }
    puts!("{}\n", mi);
}

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


use std::io::stdin;

use std::cmp::{min,max};

fn main() {
    let a = {
        let mut input = String::new();
        stdin().read_line(&mut input).unwrap();
        input.trim().chars().map(|k| k.to_digit(10).unwrap()).collect::<Vec<_>>()
    };

    let la: Vec<_> = a.iter().cloned().take(3).collect();
    let ra: Vec<_> = a.iter().cloned().skip(3).collect();

    let l: u32 = a.iter().cloned().take(3).sum();
    let r: u32 = a.iter().cloned().skip(3).sum();

    let diff = r as i32 - l as i32;

    if diff == 0 {
        println!("0");
        std::process::exit(0);
    }

    let (mut up, mut down) = if diff > 0 {
        (ra, la)
    } else {
        (la, ra)
    };

    let mut v = Vec::new();
    v.append(&mut up);
    v.append(&mut down);

    for a in v.iter_mut().skip(3) {
        *a = 9 - *a;
    }

    v.sort();

    let diff = diff.abs();

    let mut sum = 0u32;

    for (i, k) in v.into_iter().rev().enumerate() {
        if sum >= diff as u32 {
            println!("{}", i);
            std::process::exit(0);
        }
        sum += k;
    }
}


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

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

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

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

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

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

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

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

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

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

/// Verified by https://atcoder.jp/contests/arc093/submissions/3968098
mod mod_int {
    use std::ops::*;
    pub trait Mod: Copy { fn m() -> i64; }
    #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
    pub struct ModInt<M> { pub x: i64, phantom: ::std::marker::PhantomData<M> }
    impl<M: Mod> ModInt<M> {
        // x >= 0
        pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }
        fn new_internal(x: i64) -> Self {
            ModInt { x: x, phantom: ::std::marker::PhantomData }
        }
        pub fn pow(self, mut e: i64) -> Self {
            debug_assert!(e >= 0);
            let mut sum = ModInt::new_internal(1);
            let mut cur = self;
            while e > 0 {
                if e % 2 != 0 { sum *= cur; }
                cur *= cur;
                e /= 2;
            }
            sum
        }
        #[allow(dead_code)]
        pub fn inv(self) -> Self { self.pow(M::m() - 2) }
    }
    impl<M: Mod, T: Into<ModInt<M>>> Add<T> for ModInt<M> {
        type Output = Self;
        fn add(self, other: T) -> Self {
            let other = other.into();
            let mut sum = self.x + other.x;
            if sum >= M::m() { sum -= M::m(); }
            ModInt::new_internal(sum)
        }
    }
    impl<M: Mod, T: Into<ModInt<M>>> Sub<T> for ModInt<M> {
        type Output = Self;
        fn sub(self, other: T) -> Self {
            let other = other.into();
            let mut sum = self.x - other.x;
            if sum < 0 { sum += M::m(); }
            ModInt::new_internal(sum)
        }
    }
    impl<M: Mod, T: Into<ModInt<M>>> Mul<T> for ModInt<M> {
        type Output = Self;
        fn mul(self, other: T) -> Self { ModInt::new(self.x * other.into().x % M::m()) }
    }
    impl<M: Mod, T: Into<ModInt<M>>> AddAssign<T> for ModInt<M> {
        fn add_assign(&mut self, other: T) { *self = *self + other; }
    }
    impl<M: Mod, T: Into<ModInt<M>>> SubAssign<T> for ModInt<M> {
        fn sub_assign(&mut self, other: T) { *self = *self - other; }
    }
    impl<M: Mod, T: Into<ModInt<M>>> MulAssign<T> for ModInt<M> {
        fn mul_assign(&mut self, other: T) { *self = *self * other; }
    }
    impl<M: Mod> Neg for ModInt<M> {
        type Output = Self;
        fn neg(self) -> Self { ModInt::new(0) - self }
    }
    impl<M> ::std::fmt::Display for ModInt<M> {
        fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
            self.x.fmt(f)
        }
    }
    impl<M: Mod> ::std::fmt::Debug for ModInt<M> {
        fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
            let (mut a, mut b, _) = red(self.x, M::m());
            if b < 0 {
                a = -a;
                b = -b;
            }
            write!(f, "{}/{}", a, b)
        }
    }
    impl<M: Mod> From<i64> for ModInt<M> {
        fn from(x: i64) -> Self { Self::new(x) }
    }
    // Finds the simplest fraction x/y congruent to r mod p.
    // The return value (x, y, z) satisfies x = y * r + z * p.
    fn red(r: i64, p: i64) -> (i64, i64, i64) {
        if r.abs() <= 10000 {
            return (r, 1, 0);
        }
        let mut nxt_r = p % r;
        let mut q = p / r;
        if 2 * nxt_r >= r {
            nxt_r -= r;
            q += 1;
        }
        if 2 * nxt_r <= -r {
            nxt_r += r;
            q -= 1;
        }
        let (x, z, y) = red(nxt_r, r);
        (x, y - q * z, z)
    }
} // mod mod_int

macro_rules! define_mod {
    ($struct_name: ident, $modulo: expr) => {
        #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        struct $struct_name {}
        impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }
    }
}
const MOD: i64 = 998_244_353;
define_mod!(P, MOD);
type ModInt = mod_int::ModInt<P>;

// Depends on ModInt.rs
fn fact_init(w: usize) -> (Vec<ModInt>, Vec<ModInt>) {
    let mut fac = vec![ModInt::new(1); w];
    let mut invfac = vec![0.into(); w];
    for i in 1 .. w {
        fac[i] = fac[i - 1] * i as i64;
    }
    invfac[w - 1] = fac[w - 1].inv();
    for i in (0 .. w - 1).rev() {
        invfac[i] = invfac[i + 1] * (i as i64 + 1);
    }
    (fac, invfac)
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (let _ = write!(out,$($format)*););
    }
    input!(n: usize, k: i64);
    let (fac, invfac) = fact_init(n + 1);
    if k > n as i64 - 1 {
        puts!("0\n");
        return;
    }
    let k = k as usize;
    if k == 0 {
        puts!("{}\n", fac[n]);
        return;
    }
    let mut inex = ModInt::new(0);
    // Sur(n, n - k)
    for i in 0..n - k + 1 {
        let sgn = if (n - k + i) % 2 == 0 { 1 } else { MOD - 1 };
        let tmp = ModInt::new(i as i64).pow(n as i64);
        inex += tmp * sgn * fac[n - k] * invfac[i] * invfac[n - k - i];
    }
    puts!("{}\n", inex * fac[n] * invfac[n - k] * invfac[k] * 2);
}

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


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

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

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

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

    let n = input.u();
    let tt = input.i();
    let mut t = vec![0; n];
    let mut g = vec![0; n];
    let mut z = vec![0; 4];
    for i in 0..n {
        t[i] = input.i();
        g[i] = input.i();
        z[g[i] as usize] += 1;
    }
    let sumt: i32 = t.iter().sum();

    let dp2 = {
        let mut dp2 = HashMap::<(i32,i32,i32),Field>::new();
        let mut dp = HashMap::<(i32,i32,i32,i32,i32),Field>::new();
        for g in 1..4 {
            dp.insert((0,0,0,0,g), Field(1));
        }
        for _i in 0..n {
            let mut d = HashMap::<(i32,i32,i32,i32,i32),Field>::new();
            for ((h,a,b,c,l), y) in dp.into_iter() {
                let mut p = [0,a,b,c];
                let mut pf = [Field(0),Field(a),Field(b),Field(c)];
                for g in 1..4 {
                    let gu = g as usize;
                    if (h == 0 && g != l) || (h > 0 && g == l) {
                        continue;
                    }
                    p[gu] += 1;
                    pf[gu] += Field(1);
                    if (1..4).all(|i| p[i] <= z[i]) {
                        let key = (h + 1, p[1], p[2], p[3], g);
                        let res = y * pf[g as usize] + *d.get(&key).unwrap_or_default();
                        d.insert(key, res);
                    }
                    p[gu] -= 1;
                    pf[gu] -= Field(1);
                }
            }

            for (&(_,a,b,c,_),&x) in d.iter() {
                let key = (a,b,c);
                let res = *dp2.get(&key).unwrap_or_default();
                dp2.insert(key, res + x);
            }
            dp = d;
            // println!("\n-----------------------: {}", _i);
            // for ((h,a,b,c,g),x) in dp.iter() {
            // println!("{} {} {} {} {}: {}", h,a,b,c,g,x);
            // }
        }
        dp2
    };
    // eprintln!("DP2");
    // for ((a,b,c),x) in dp2.iter() {
        // println!("dp2    {} {} {} : {}", a,b,c,x);
    // }

    let dp1 = {
        let mut st = [0; 3];
        st[2] = 1;
        st[1] = st[2] * (z[2] + 1);
        st[0] = st[1] * (z[1] + 1);
        let st = st;
        let sz = (st[0] * (sumt + 1)) as usize;

        let mut aa = vec![Field(0); sz];
        let mut dp = HashSet::<i32>::new();
        dp.insert(0);
        aa[0] = Field(1);
        for i in 0..n {
            if g[i] == 3 { continue; }

            let mut d = HashSet::<i32>::new();
            let mut a = vec![Field(0); sz];
            let x = t[i];
            let g = g[i] as usize;
            for &s in dp.iter() {
                let key = s + (x * st[0]) + st[g];
                d.insert(key);
                a[key as usize] += aa[s as usize];
            }
            for key in d.into_iter() {
                let s = key as usize;
                aa[s] += a[s];
                dp.insert(key);
            }
        }
        let mut dp1 = HashMap::<(i32,i32,i32),Field>::new();
        for s in dp.into_iter() {
            let t = s / st[0];
            let a = s % st[0] / st[1];
            let b = s % st[1] / st[2];
            dp1.insert((t,a,b),aa[s as usize]);
        }
        dp1
    };
    // eprintln!("DP1");
    // for ((a,b,c),x) in dp1.iter() {
        // println!("dp1    {} {} {} : {}", a,b,c,x);
    // }

    let dp3 = {
        let mut st = [0; 4];
        st[3] = 1;
        st[0] = st[3] * (z[3] + 1);
        let st = st;
        let sz = (st[0] * (sumt + 1)) as usize;

        let mut aa = vec![Field(0); sz];
        let mut dp = HashSet::<i32>::new();
        dp.insert(0);
        aa[0] = Field(1);
        for i in 0..n {
            if g[i] != 3 { continue; }

            let mut d = HashSet::<i32>::new();
            let mut a = vec![Field(0); sz];
            let x = t[i];
            let g = g[i] as usize;
            for &s in dp.iter() {
                let key = s + (x * st[0]) + st[g];
                d.insert(key);
                a[key as usize] += aa[s as usize];
            }
            for key in d.into_iter() {
                let s = key as usize;
                aa[s] += a[s];
                dp.insert(key);
            }
        }
        let mut dp3 = HashMap::<(i32,i32),Field>::new();
        for s in dp.into_iter() {
            let t = s / st[0];
            let c = s % st[0] / st[3];
            dp3.insert((t,c),aa[s as usize]);
        }
        dp3
    };
    // eprintln!("DP3");
    // for ((a,b),x) in dp3.iter() {
        // println!("dp3    {} {} : {}", a,b,x);
    // }

    let dp1 = {
        let mut dp = HashMap::<(i32,i32,i32),Field>::new();
        for ((tab,a,b),res1) in dp1 {
            let tc = tt - tab;
            if tc < 0 { continue; }
            for c in 0..=z[3] {
                if let Some(&res2) = dp3.get(&(tc,c)) {
                    let res3 = *dp.get(&(a,b,c)).unwrap_or_default();
                    dp.insert((a,b,c), res3 + res1*res2);
                }
            }
        }
        dp
    };
    // println!("DP1");
    // println!("DP1");
    // for ((a,b,c),&x) in dp1.iter() {
        // println!("dpX    {} {} {} : {}", a,b,c,x);
    // }

    let mut sol = Field::new_unchecked(0);
    for a in 0..=z[1] as i32 {
        for b in 0..=z[2] as i32 {
            for c in 0..=z[3] as i32 {
                let x = *dp1.get(&(a,b,c)).unwrap_or_default();
                let y = *dp2.get(&(a,b,c)).unwrap_or_default();
                sol += x * y;
            }
        }
    }
    println!("{}", sol);
}


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

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

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

const M: i64 = 1_000_000_007;

// fn mul(a: i64, b: i64) -> i64 { a * b % M }
fn add(a: i64, b: i64) -> i64 {
    let mut x = (a + b) % M;
    if x < 0 { x += M; }
    x
}

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

    let n = input.u();
    let tt = input.i();
    let mut t = vec![0; n];
    let mut g = vec![0; n];
    let mut z = vec![0; 4];
    for i in 0..n {
        t[i] = input.i();
        g[i] = input.i();
        z[g[i] as usize] += 1;
    }

    let f = |a,b| if a == b { 1 } else { 0 };

    let dp1 = {
        let mut dp = HashMap::<(i32,i32,i32,i32),i64>::new();
        dp.insert((0,0,0,0), 1);
        for i in 0..n {
            let mut d = HashMap::<(i32,i32,i32,i32),i64>::new();
            let x = t[i];
            let g = g[i];
            for (&(t,a,b,c), &y) in dp.iter() {
                let key = (t + x, a + f(g, 1), b + f(g, 2), c + f(g, 3));
                let res = *d.get(&key).unwrap_or(&0);
                d.insert(key, add(res, y));
            }
            for (key, y) in d.into_iter() {
                let res = *dp.get(&key).unwrap_or(&0);
                dp.insert(key, add(res, y));
            }
        }
        dp
    };
    //  for ((t,a,b,c),x) in dp1.iter() {
        //  println!("dp1    {} {} {} {} : {}", t,a,b,c,x);
    //  }

    let dp2 = {
        let mut dp2 = HashMap::<(i32,i32,i32),i64>::new();
        let mut dp = HashMap::<(i32,i32,i32,i32,i32),i64>::new();
        for g in 1..4 {
            dp.insert((0,0,0,0,g), 1);
        }
        for _i in 0..n {
            let mut d = HashMap::<(i32,i32,i32,i32,i32),i64>::new();
            for ((h,a,b,c,l), y) in dp.into_iter() {
                let mut p = [0,a,b,c];
                for g in 1..4 {
                    if (h == 0 && g != l) || (h > 0 && g == l) {
                        continue;
                    }
                    p[g as usize] += 1;
                    if (1..4).all(|i| p[i] <= z[i]) {
                        let key = (h + 1, p[1], p[2], p[3], g);
                        let res = add(y * p[g as usize] as i64, *d.get(&key).unwrap_or(&0));
                        d.insert(key, res);
                    }
                    p[g as usize] -= 1;
                }
            }

            for (&(_,a,b,c,_),&x) in d.iter() {
                let key = (a,b,c);
                let res = *dp2.get(&key).unwrap_or(&0);
                dp2.insert(key, add(res, x));
            }
            dp = d;
            // println!("\n-----------------------: {}", _i);
            // for ((h,a,b,c,g),x) in dp.iter() {
            // println!("{} {} {} {} {}: {}", h,a,b,c,g,x);
            // }
        }
        dp2
    };
    //  for ((a,b,c),x) in dp2.iter() {
        //  println!("dp2    {} {} {} : {}", a,b,c,x);
    //  }

    let mut sol: i64 = 0;
    for a in 0..z[1]+1 {
        let a = a as i32;
        for b in 0..z[2]+1 {
            let b = b as i32;
            for c in 0..z[3]+1 {
                let c = c as i32;
                let x = dp1.get(&(tt,a,b,c)).unwrap_or(&0);
                let y = dp2.get(&(a,b,c)).unwrap_or(&0);
                sol = add(sol, x * y);
            }
        }
    }
    println!("{}", sol);
}


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

use std::collections::*;
use std::io::*;
use std::cmp::{max, min, Ordering};
use std::f64::consts::*;
use std::mem::{swap, size_of_val, size_of};
use std::fs::File;
use std::rc::*;
use std::ascii::*;
use std::ops::*;
use std::num::*;
use std::process::*;
//use std::ptr::*;
use std::iter::{once, repeat};

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

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

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

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

macro_rules! read {
    () => {};
	($inf:ident, $t:ty) => ($inf.read_word().parse::<$t>().expect("Parsing error"));
	($inf:ident, $($t:ty),*) => (($($inf.read_word().parse::<$t>().expect("Parsing error")),*));
}
fn gcd<T>(mut a: T, mut b: T) -> T
	where T: ShrAssign + BitAnd<Output=T> + Ord + From<u8> + Clone + SubAssign + ShlAssign<usize> + Copy
{
	let one = T::from(1);
	let zero = T::from(0);
	let mut ans = 0;
	if a < b {
		swap(&mut a, &mut b);
	}
	while b > zero {
		if (a & one > zero) && (b & one > zero) {
			a -= b;
		} else if a & one > zero {
			b >>= one;
		} else if b & one > zero {
			a >>= one;
		} else {
			ans += 1;
			a >>= one;
			b >>= one;
		}
		if a < b {
			swap(&mut a, &mut b);
		}
	}
	a <<= ans;
	a
}

fn powmod<X, Y>(mut base: X, mut exp: Y, mm: X) -> X
	where X: Copy + Clone + Mul<Output=X> + Rem<Output=X> + From<u8>,
	      Y: ShrAssign + Copy + Clone + BitAnd<Output=Y> + From<u8> + Ord
{
	let mut res = X::from(1);
	while exp > Y::from(0) {
		if exp & Y::from(1) > Y::from(0) {
			res = res * base % mm;
		}
		base = base * base % mm;
		exp >>= Y::from(1);
	}
	res
}

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

fn solve<Inner: BufRead, Output: Write>(inf: &mut Input<Inner>, ouf: &mut Output) {
	let n = read!(inf,usize);
	let mut a = vec![0; n];
	for i in 0..n {
		a[i] = read!(inf,usize);
	}
	a.sort_unstable();
	a.dedup();
	let mut pos = 0;
	while pos < n && a[pos] == 0 {
		pos += 1;
	}
	writeln!(ouf, "{}", a.len() - pos);
}


use std::io;
use std::fs::File;

fn main() {
    let stdin = io::stdin();
    let buf :Box<io::BufRead> = if cfg!(feature = "intxt") {
        eprintln!("file mode");
        let file = File::open("in.txt").unwrap();
        Box::new(io::BufReader::new(file))
    } else {
        eprintln!("stdin mode");
        Box::new(stdin.lock())
    };
    let mut sc = Scanner::new(buf);

    let n :i32 = sc.next();
    let mut vec = Vec::new();
    for _ in 0..n {
        let a :i32 = sc.next();
        vec.push(a);
    }
    vec.sort();
    vec.reverse();
    let mut a = vec[0];
    let mut cnt = 1;
    for x in vec {
        if x != a {
            a = x;
            if x > 0 {
                cnt += 1;
            }
        }
    }
    println!("{}", cnt);
}

struct Scanner<B: io::BufRead> {
    reader: B,
    buffer: Vec<String>,
}

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

    fn next<T: std::str::FromStr>(&mut self) -> T
    where
        T::Err: std::fmt::Debug,
    {
        if let Some(s) = self.buffer.pop() {
            T::from_str(&s).unwrap()
        } else {
            let mut s = String::new();
            let r = self.reader.read_line(&mut s).unwrap();
            assert!(r > 0);
            self.buffer = s.split_whitespace().rev().map(String::from).collect();
            return self.next();
        }
    }
}


fn main() {
    let mut input = String::new();
    use std::io;
    use std::io::prelude::*;
    io::stdin().read_to_string(&mut input).unwrap();

    let mut it = input.split_whitespace();

    let n: usize = it.next().unwrap().parse().unwrap();

    let a: Vec<usize> = it.map(|x| x.parse().unwrap()).collect();

    let mut set = [false; 601];

    for a in a {
        set[a] = true;
    }

    let ans = set[1..].iter().filter(|&&x| x).count();

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


macro_rules! parse_line {
    ($t: ty) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let a_str = a_str.trim();
        a_str.parse::<$t>().expect("parse error")
    });
    ($($t: ty),+) => ({
        let mut a_str = String::new();
        std::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"),
            )+
        )
    })
}

macro_rules! parse_line_to_vec {
    ($t: ty) => {{
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        (a_str
            .split_whitespace()
            .map(|x| x.parse::<$t>().unwrap())
            .collect::<Vec<$t>>())
    }};
}

fn solve() {
    let (n, m) = parse_line!(usize, usize);
    let l = parse_line_to_vec!(usize);
    let mut result = vec![0; n];
    let mut ok = true;
    for i in 1..m {
        let leader = l[i - 1] - 1;
        let mut diff = (n + l[i] - l[i - 1]) % n;
        if diff == 0 {
            diff = n;
        }
        if result[leader] == 0 {
            result[leader] = diff;
        }else if result[leader] != diff {
            ok = false;
        }
    }
    for i in 0..n {
        if result[i] == 0 {
            continue;
        }
        let mut local = true;
        for j in 0..i {
            local &= result[i] != result[j];
        }
        ok &= local;
    }
    if !ok {
        return println!("-1");
    }
    let mut s = std::collections::HashSet::<usize>::new();
    s.extend(result.iter());
    let mut next = 1;
    for i in 0..n {
        if result[i] != 0 {
            continue;
        }
        while s.contains(&next) {
            next += 1;
        }
        result[i] = next;
        next += 1;
    }
    for x in result {
        print!("{} ", x);
    }
    println!();
}

fn main() {
    let tests = 1; // parse_line!(usize);
    for _ in 0..tests {
        solve();
    }
}


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

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

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

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

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

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

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

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

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

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

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

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

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

fn run() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let s: Vec<usize> = s.trim().chars().map(|c| c.to_digit(10).unwrap() as usize).collect();
    let mut ans = s.iter().fold(ModInt::zero(), |s, a| ModInt(10) * s + ModInt(*a as u32));
    for x in 1..=9 {
        for y in 1..x {
            if gcd(x, y) > 1 {
                continue;
            }
            // キャリー抜きで確定してる桁数の範囲でn以下なら0
            // xのキャリーがいくつ
            // yのキャリーがいくつ
            // xの出現
            // yの出現
            let m = 9 / x;
            let init = vec![vec![vec![vec![vec![ModInt::zero(); 1 << m]; 1 << m]; 9]; 9]; 2];
            let mut now = init.clone();
            let mut next = init.clone();
            now[0][0][0][0][0] = ModInt::one();
            for &digit in s.iter().rev() {
                next.clone_from(&init);
                for (cond, v) in now.iter().enumerate() {
                    for (cx, v) in v.iter().enumerate() {
                        for (cy, v) in v.iter().enumerate() {
                            for (bit_x, v) in v.iter().enumerate() {
                                for (bit_y, &v) in v.iter().enumerate() {
                                    for d in 0..10 {
                                        let carry_x = (cx + d * x) / 10;
                                        let carry_y = (cy + d * y) / 10;
                                        let dx = (cx + d * x) % 10;
                                        let dy = (cy + d * y) % 10;
                                        let nx = bit_x | if dx > 0 && dx % x == 0 {1 << (dx / x - 1)} else {0};
                                        let ny = bit_y | if dy > 0 && dy % y == 0 && dy / y <= m {1 << (dy / y - 1)} else {0};
                                        if dx < digit {
                                            next[0][carry_x][carry_y][nx][ny] += v;
                                        } else if dx > digit {
                                            next[1][carry_x][carry_y][nx][ny] += v;
                                        } else {
                                            next[cond][carry_x][carry_y][nx][ny] += v;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                std::mem::swap(&mut next, &mut now);
            }
            for (i, v) in now[0][0][0].iter().enumerate() {
                for (j, &v) in v.iter().enumerate() {
                    let mut ok = false;
                    for k in 0..m {
                        ok |= ((i >> k) & 1 == 1) && ((j >> k) & 1 == 1);
                    }
                    if ok && v.0 > 0 {
                        ans += v + v;
                    }
                }
            }
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}


use std::io::stdin;

fn main() {
    let mut buf = String::new();
    for _i in 0..3 {
        let _ = stdin().read_line(&mut buf);
        buf = buf.trim_end().to_string();
    }

    let x = buf.as_bytes();
    let mut ans = true;
    for i in 0..x.len()/ 2 {
        ans = ans && x[i] == x[x.len() - i - 1];
    }

    println!("{}", if ans { "YES" } else { "NO" });
}


fn getline() -> String{
    let mut __ret = String::new();
    std::io::stdin().read_line(&mut __ret).ok();
    return __ret;
}

fn main() {
    let s = getline();
    let inp:Vec<_> = s.trim().split(' ').collect();
    let mut n: i32 = inp[0].parse().unwrap();
    let k: usize = inp[1].parse().unwrap();
    let mut ans = vec![];
    for i in 2..n-1 {
        while n%i == 0 {
            if ans.len() == k-1 {
                break;
            }
            ans.push(i);
            n /= i;
        }
    }
    if ans.len() == k-1 && n != 1 {
        for e in &ans {
            print!("{} ",e);
        }
        println!("{}",n);
    }else{
        println!("-1");
    }
}


#![allow(dead_code)]
#![allow(unused_imports)]
use std::cmp::{min, max};
use std::io::{BufWriter, stdin, stdout, Write};
const BITS: usize = 19;

#[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 out = &mut BufWriter::new(stdout());

    let n: i32 = scan.next::<i32>();
    let m: i32 = scan.next::<i32>();

    let mut arr: Vec<(i32, i32)> = Vec::new();

    for _i in 0..m {
        let a: i32 = scan.next::<i32>();
        let b: i32 = scan.next::<i32>();
        arr.push((a, b));
    }

    arr.sort_by(|a, b| a.1.cmp(&b.1));
    arr.reverse();

    let mut total: i32 = 0;
    let mut total_boxes: i32 = 0;

    'outer: for (a, b) in arr.iter() {
        if total_boxes >= n {
            break;
        }
        'inner: for _i in 0..*a {
            if total_boxes >= n {
                break 'outer;
            }
            total_boxes += 1;
            total += *b;
        }
    }

    writeln!(out, "{}", total);
}