#![allow(non_snake_case, unused_imports, deprecated, dead_code)]

// Input macros
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)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $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, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::<Vec<char>>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect("Parse error") }; }

// Module
use std::cmp::{min,max};
use std::collections::{VecDeque,HashSet,HashMap,BinaryHeap};
// Module for v1.15.1
use std::ascii::AsciiExt; // deprecated since 1.26.0: use inherent method instead

// Functions

// Main
fn main() {

    input! {
        s1: String,
        s2: String
    }

    let s1 = s1.to_lowercase();
    let s2 = s2.to_lowercase();

    let mut ans = 0;
    if s1 < s2 {
        ans = -1;
    } else if s1 > s2 {
        ans = 1;
    }

    println!("{}", ans);

}


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

pub struct Scanner<U: Sized + Read> {
    pub buffer: Vec<String>,
    pub reader: U,
}
impl<U: Sized + Read> Scanner<U> {
    pub 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();
            self.reader.read_to_string(&mut input).expect("Failed read");
            self.buffer = input.lines().rev().map(String::from).collect();
        }
    }

    pub fn new(reader: U) -> Self {
        return Scanner {
            buffer: vec![],
            reader,
        };
    }
}
pub fn solution_of_p112a(input: &mut Read, out: &mut Write) {
    let mut scanner = Scanner::new(input);
    let arr1: Vec<char> = scanner
        .next::<String>()
        .to_ascii_lowercase()
        .chars()
        .collect();
    let arr2: Vec<char> = scanner
        .next::<String>()
        .to_ascii_lowercase()
        .chars()
        .collect();

    let res = lexicographical_order(arr1, arr2);
    write!(out, "{}\n", res).ok();
}

pub fn lexicographical_order(arr1: Vec<char>, arr2: Vec<char>) -> i32 {
    let l = arr1.len(); // assume the 2 string has the same length
    for i in 0..l {
        let u1 = arr1[i] as u8;
        let u2 = arr2[i] as u8;
        if u1 < u2 {
            return -1;
        } else if u1 > u2 {
            return 1;
        }
    }
    return 0;
}

fn main() {
    solution_of_p112a(&mut stdin(), &mut stdout());
}


use std::io::stdin;
use std::collections::HashSet;

fn read_line<'a>() -> Result<String, Box<std::error::Error>> {
    let mut line = String::new();
    stdin().read_line(&mut line)?;

    Ok(line.trim().to_owned())
}

fn main() -> Result<(), Box<std::error::Error>> {
    let line = read_line()?;
    let mut nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap());

    let _ = nums.next().unwrap();
    let mut b = nums.next().unwrap();

    let line = read_line()?;

    let nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap())
        .collect::<Vec<_>>();

    let evency = nums
        .iter()
        .map(|n| if n % 2 == 0 { 1 } else { -1 })
        .collect::<Vec<_>>();

    let mut split_points = HashSet::new();
    let mut s = 0;

    for (i, e) in evency[..evency.len() - 1].iter().enumerate() {
        s += e;

        // println!("{}, {}, {}", i, s, e);

        if s == 0 {
            split_points.insert(i);
        }
    }

    let mut diffs = nums
        .iter()
        .zip(&nums[1..])
        .map(|(&prev, &curr)| (curr - prev).abs())
        .enumerate()
        .collect::<Vec<_>>();

    diffs.sort_unstable_by_key(|&(_, diff)| diff);

    // println!("diffs: {:?}", diffs);
    // println!("split_points: {:?}", split_points);

    let mut ans = 0;

    for (i, diff) in diffs {
        if split_points.contains(&i) && b >= diff {
            // println!("split at {}, price {}, current budget: {}", i, diff, b);

            ans += 1;
            b -= diff;
        }
    }

    println!("{}", ans);

    Ok(())
}


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

fn cut( accum: &Vec<(i64,i64)>, nums: &Vec<i64>, s: usize, e: usize ) -> (i64,i64) {
    //println!("cut range: {},{}", s,e);
    for idx in s..e {
        let b = ( accum[e-1].0 - accum[idx].0, accum[e-1].1 - accum[idx].1 );
        let a = if s > 0 {
            ( accum[idx].0 - accum[s-1].0, accum[idx].1 - accum[s-1].1 )
        } else {
            ( accum[idx].0, accum[idx].1 )
        };
        //println!("idx:{}, a: {:?}, b: {:?}", idx, a, b );
        if b.0 == b.1 && b.0 != 0 && a.0 == a.1 && a.0 != 0 {
            //make a cut between (idx, idx+1)
            //println!("make a cut between {}, {}", idx, idx+1 );
            return (idx as i64,idx as i64 + 1)
        }
    }
    return (-1,-1)
}

fn main() {

    use std::collections::{HashMap,HashSet, BinaryHeap};

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

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

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

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

    let nums = input_strs.iter().skip(2).cloned().collect::< Vec<i64> >();

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

    let mut eo = nums.iter().map( |x| if *x % 2 == 0 { true } else { false } ).collect::<Vec< bool >>();

    let mut count_e = 0;
    let mut count_o = 0;
    let accum = eo.iter().enumerate().map(|(k,x)| {
        if *x == true { count_e += 1; } else { count_o += 1; }
        ( count_e, count_o )
    } ).collect::< Vec< (i64,i64) > >();

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

    let mut cut_idxs = cut( &accum, &nums, 0, nums.len() );
    let mut accum_cost = 0;
    let mut num_cuts = 0;

    let mut possible_cuts = vec![];
    loop {
        if cut_idxs.0 == -1 || cut_idxs.1 == -1 {
            break;
        }
        let cost_cut = (nums[cut_idxs.0 as usize] - nums[cut_idxs.1 as usize]).abs();

        cut_idxs = cut( &accum, &nums, cut_idxs.1 as usize, nums.len() );
        possible_cuts.push( ( cost_cut, cut_idxs ) );
    }

    possible_cuts.sort();

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

    for i in possible_cuts.iter() {
        if accum_cost + i.0 <= b {
            accum_cost += i.0;
            num_cuts += 1;
        } else {
            break;
        }
    }

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


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

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

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

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

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

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

fn main() {
    let n = get!(u64);
    let m9 = (0..)
        .take_while(|&x| (2 * n - 1) >= 10u64.pow(x as u32) - 1)
        .last()
        .unwrap();

    let mut ans = 0;
    for i in 0.. {
        let y = i as u64 * 10u64.pow(m9 as u32) + 10u64.pow(m9 as u32) - 1;
        if y > 2 * n - 1 {
            break;
        }
        if y <= 2 * n - 1 && y > 0 {
            if y > n {
                ans += (n - (y - n) - 1) / 2 + 1;
            } else {
                ans += (y - 1) / 2;
            }
        }
    }

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


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

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

    if 2 * n < 10 {
        let ans = n * (n - 1) / 2;
        println!("{}", ans);
        return;
    }

    let mut max_nine_count = 0;
    let mut k = 2 * n;
    while k >= 10 {
        max_nine_count += 1;
        k /= 10;
    }

    let mut ans = 0;

    for mut i in 1..k + 1 {
        for _ in 0..max_nine_count {
            i *= 10;
        }
        let j = i / 2;
        let p = std::cmp::min(i - 2, n) - j + 1;
        ans += p;
    }

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


use std::collections::HashMap;
use std::io;

fn to_pairs(line: &str) -> Vec<(i32, i32)> {
	let mut iter = line.trim().split_whitespace();
	let mut ret = Vec::new();
	while let Some(x) = iter.next() {
		ret.push((x.parse().unwrap(),
		          iter.next().unwrap().parse().unwrap()));
	}
	ret.sort();
	return ret
}

fn get_unique(s1: (i32, i32), s2: (i32, i32)) -> Option<i32> {
	let mut v = Vec::new();
	v.push(s1.0);
	v.push(s1.1);
	v.push(s2.0);
	v.push(s2.1);
	v.sort();
	v.dedup();
	if v.len() != 3 { return None; }
	for x in v {
		if (x == s1.0 || x == s1.1) && (x == s2.0 || x == s2.1) {
			return Some(x);
		}
	}
	return None;
}

fn get_only_bit(x: i32) -> Option<i32> {
	let mut count = 0;
	let mut last = 0;
	for i in 1..10 {
		if (x >> i & 1) != 0 {
			count += 1;
			last = i;
		}
	}
	if count == 1 { return Some(last); }
	return None;
}

fn solve(s1: Vec<(i32, i32)>, s2: Vec<(i32, i32)>) -> i32 {
	let mut va: HashMap<(i32, i32), i32> = HashMap::new();
	let mut vb: HashMap<(i32, i32), i32> = HashMap::new();
	let mut vab = 0;
	for a in s1.iter() {
		for b in s2.iter() {
			if let Some(x) = get_unique(*a, *b) {
				va.entry(*a)
					.and_modify(|e| { *e |= 1 << x })
					.or_insert(1 << x);
				vb.entry(*b)
					.and_modify(|e| { *e |= 1 << x })
					.or_insert(1 << x);
				vab |= 1 << x;
			}
		}
	}
	if let Some(x) = get_only_bit(vab) { return x; }
	for (_, v) in va.iter() {
		if let None = get_only_bit(*v) { return -1; }
	}
	for (_, v) in vb.iter() {
		if let None = get_only_bit(*v) { return -1; }
	}
	return 0;
}

fn main() -> io::Result<()> {
	let f = io::stdin();
	let mut line = String::new();
	f.read_line(&mut line)?;
	line.clear();
	f.read_line(&mut line)?;
	let s1 = to_pairs(&line);
	line.clear();
	f.read_line(&mut line)?;
	let s2 = to_pairs(&line);
	println!("{}", solve(s1, s2));

	Ok(())
}


use std::io;
use std::str::FromStr;
use std::collections::HashMap;

fn get_num() -> i32 {
    let mut input = String::new();

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

    i32::from_str(input.trim()).unwrap()
}

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

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

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

fn main() {
    let n = get_num();
    let a = get_nums();

    let mut m = HashMap::new();
    let mut min_pos = -1;
    let mut max_pos = -1;
    for (idx, e) in a.iter().enumerate() {
        m.insert(*e, (idx + 1) as i32);

        if *e == n {
            max_pos = (idx + 1) as i32;
        }

        if *e == 1 {
            min_pos = (idx + 1) as i32;
        }
    }

    let mut d = (max_pos - min_pos).abs();
    for i in 1..=n {
        if i == *m.get(&1).unwrap() || i == *m.get(&n).unwrap() {
            continue;
        }

        d = std::cmp::max(d, (i - max_pos).abs());
        d = std::cmp::max(d, (i - min_pos).abs());
    }

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


#![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 n = get_numbers::<usize>(&line)[0];
    line.clear();
    input.read_line(&mut line).unwrap();
    let arr = get_numbers::<usize>(&line);

    let min_i = arr.iter().position(|&v| v == 1).unwrap();
    let max_i = arr.iter().position(|&v| v == n).unwrap();

    let d_min = f64::abs(min_i as f64 - ((n-1) as f64 / 2.0)); // distance to center
    let d_max = f64::abs(max_i as f64 - ((n-1) as f64 / 2.0));

    // pick closest to center to move
    let d = if d_min < d_max {
        if min_i < max_i { // move min to 0
            max_i
        } else {
            (n-1)-max_i // move min to end
        }
    } else {
        if max_i < min_i {
            min_i
        } else {
            (n-1)-min_i
        }
    };

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

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


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

    let n = input.u();
    let a = input.vi(n);
    let i = a.iter().position(|&x| x == 1).unwrap();
    let j = a.iter().position(|&x| x == n as i32).unwrap();
    let sol = i.max(j).max(n - i - 1).max(n - j - 1);
    println!("{}", sol);
}


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.take(n).map(|x| x.parse().unwrap()).collect();

    let mut outmost = 101;

    for (i, a) in a.into_iter().enumerate() {
        if a == 1 || a == n {
            if i < outmost {
                outmost = i;
            }
            if n - 1 - i < outmost {
                outmost = n - 1 - i;
            }
        }
    }

    let ans = n - 1 - outmost;

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


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

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

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

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

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

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

fn main() {
    let s: Vec<char> = util::line().chars().collect();

    let mut dp = vec![vec![0; 3]; s.len()];

    for (i, &c) in s.iter().enumerate() {
        match c {
            'Q' => {
                for k in 0..i {
                    dp[i][2] += dp[k][1];
                }
                dp[i][0] += 1;
            }
            'A' => {
                for k in 0..i {
                    dp[i][1] += dp[k][0];
                }
            }
            _ => (),
        }
    }

    println!("{}", dp.iter().map(|v| v[2]).sum::<usize>());
}


use std::io;

fn main () {
  let mut s = String::new();
  io::stdin().read_line(&mut s);
  let chars : Vec<char> = s.chars().collect();
  let mut cnt = 0;
  for i in 0..s.len () {
    for j in i+1..s.len () {
      for k in j+1..s.len ()  {
        if chars[i] == 'Q' && chars[j] == 'A' && chars[k] == 'Q' {
          cnt+=1;
          }}}}
  println!("{}", cnt);
}


fn _main() {
    let mut line = String::new();
    std::io::stdin()
        .read_line(&mut line)
        .expect("failed to read");
    let line: Vec<char> = line.chars().collect();
    let mut cnt = 0usize;
    for i in 0..line.len() {
        for j in i + 1..line.len() {
            for k in j + 1..line.len() {
                if line[i] == 'Q' && line[j] == 'A' && line[k] == 'Q' {
                    cnt += 1;
                }
            }
        }
    }
    println!("{}", cnt);
}

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


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

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

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

//

fn run() {
    input! {
        s: chars,
    }
    let mut ans = 0;
    for (i, a) in s.iter().enumerate() {
        for (j, b) in s[..i].iter().enumerate() {
            for c in s[..j].iter() {
                if *a == 'Q' && *b == 'A' && *c == 'Q' {
                    ans += 1;
                }
            }
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}


/// ========== 入力用マクロ ====================================================
/// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
/// FromStr型, Vec<T: FromStr>, Vec<char>, に対応;
///
/// 入力と平行して処理したいときには使えない -> 後述の read() を使用
#[macro_export]
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_export]
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_export]
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")
    };
}

// ========== 常用関数 =======================================================
pub use std::f64::consts::PI;

// 10^9 + 7 で割ったあまりを出力してください
pub const MOD: u64 = 1_000_000_007;

// atcoder文字列, 使うときは`main()`内にコピペ
// let atcoder: Vec<char> = vec!['a', 't', 'c', 'o', 'd', 'e', 'r'];

/// 標準入力から
/// 空白文字で囲まれた1つのトークンを
/// 指定の型に変換する
pub fn read<T: std::str::FromStr>() -> T {
    use std::io::Read;
    let stdin = std::io::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")
}

/// 標準入力から1行読み取り
/// 空白文字で区切って
/// 指定の型の`Vec`に格納する
pub 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()
}

/// ユークリッドの互除法より
/// 2数の最大公約数を求める
pub fn gcd(arg1: usize, arg2: usize) -> usize {
    let mut u = if arg1 > arg2 { arg1 } else { arg2 };
    let mut v = if arg1 > arg2 { arg2 } else { arg1 };
    let mut r: usize;
    while v != 0 {
        r = u % v;
        u = v;
        v = r;
    }
    u
}

/// `Vec<usize>` に対して順に `gcd()` を適用して
/// 配列全体の最大公約数を求める
pub fn gcd_vec(v: &[usize]) -> usize {
    let mut r = v[0];
    for i in &v[1..] {
        r = gcd(r, *i);
    }
    r
}

/// `gcd()` を利用して2数の最小公倍数を求める
pub fn lcm(arg1: usize, arg2: usize) -> usize {
    arg1 * arg2 / gcd(arg1, arg2)
}

/// `Vec<usize>` に対して順に`lcm()` を適用して
/// 配列全体の最小公倍数を求める
pub fn lcm_vec(v: &[usize]) -> usize {
    let mut r = v[0];
    for i in &v[1..] {
        r = lcm(r, *i);
    }
    r
}

/// 与えられた `char` が母音であれば `true` を返す
pub fn is_vowel(c: char) -> bool {
    match c {
        'a' | 'i' | 'u' | 'e' | 'o' => true,
        _                           => false,
    }
}

/// プログラムを終了
pub fn exit() {
    std::process::exit(0)
}

// ========== main() ==========================================================

fn main() {
    input! {
        s: chars
    }

    let mut a_whr = Vec::new();
    for i in 1..s.len()-1 {
        if s[i] == 'A' {
            a_whr.push(i);
        }
    }

    let mut ans = 0;
    for i in a_whr {
        ans += s[..i].iter().filter(|c| **c == 'Q').count() *
            s[i+1..].iter().filter(|c| **c == 'Q').count();
    }
    println!("{}", ans);
}


fn main() {
    let input = input_vec_chars();
    let d: Vec<char> = input
        .into_iter()
        .filter(|c| *c == 'Q' || *c == 'A').collect();

    let mut count = 0;

    for (i, elm) in d.iter().enumerate() {
        if *elm == 'Q' {
            for j in i+1..d.len() {
                if d[j] == 'A' {
                    for k in j+1..d.len() {
                        if d[k] == 'Q' {
                            count += 1;
                        }
                    }
                }
            }
        }
    }
    println!("{:?}", count);
}

fn input_str() -> String {
    let mut buff = String::new();
    std::io::stdin().read_line(&mut buff).expect("Err");
    buff
}

fn input_u64() -> u64 {
    input_str().trim().parse().unwrap()
}

fn input_vec<T>(sep: &str) -> Vec<T>
where
    T: std::str::FromStr,
    <T as std::str::FromStr>::Err: std::fmt::Debug,
{
    input_str().trim().split(sep).map(|c| c.parse::<T>().expect("Err pars")).collect()
}

fn input_vec_chars() -> Vec<char> {
    input_str().trim().chars().collect()
}


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 count = 0;

    let mut scanner = Scanner::default();
    let s = scanner.next::<String>();

    let s_chars = s.chars().collect::<Vec<char>>();

    let mut first_q = vec![0; s_chars.len()];
    let mut a = vec![];

    first_q[0] = if s_chars[0] == 'Q' { 1 } else { 0 };

    for i in 1..s_chars.len() {
        first_q[i] = first_q[i - 1];
        match s_chars[i] {
            'Q' => {
                first_q[i] += 1;
            }
            'A' => a.push(i),
            _ => (),
        }
    }

    for i in a {
        count += first_q[i] * (first_q.last().unwrap() - first_q[i]);
    }

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


#[allow(unused_imports)]
use std::io;
use std::mem::size_of_val;
use std::cmp::{max, min};
use std::rc::Rc;
use std::collections::btree_map::BTreeMap;
use std::io::{Write, BufRead};
use std::collections::HashMap;
use std::ptr::write_volatile;

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

#[allow(unused)]
fn read_strings() -> Vec<String> {
    let mut string: String = String::new();
    std::io::stdin().read_line(&mut string).unwrap();
    let mut v = Vec::new();
    for value in string.split_whitespace() {
        v.push(value.to_string());
    }
    v
}

#[allow(unused)]
fn read_array_i32() -> Vec<i32> {
    let mut string: String = String::new();
    std::io::stdin().read_line(&mut string).unwrap();
    string.split_whitespace().map(|x| x.parse::<i32>().unwrap()).collect()
}

#[allow(unused)]
fn read_array_usize() -> Vec<usize> {
    let mut string: String = String::new();
    std::io::stdin().read_line(&mut string).unwrap();
    string.split_whitespace().map(|x| x.parse::<usize>().unwrap()).collect()
}

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

// mod math;
// mod binary_search;
// mod graph;
// mod structure;
// mod fibonacci;
// mod string;
// mod permutations;

// mod patterns;

#[allow(dead_code)]
fn memory_properties<T>(value: &T)
    where
        T: std::fmt::Display + ?Sized,
{
    println!(
        "Variable address in memory = {:p}, Allocated bytes for type = {}",
        value,
        size_of_val(value)
    );
}

#[allow(unused_macros)]
macro_rules! sum {
    ($($x:expr), *) => {
        {
            let mut res = 0;
            $(res += $x;)*
            res
        }
    };
}

static mut array: [[u8;101];101] = [[0u8; 101]; 101];

fn main() {
    use std::io::Write;
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());

    let mut ans = 0;
    let s = gets();
    let bytes = s.as_bytes();

    for i in 0..bytes.len() {
        if bytes[i] == 'Q' as u8 {
            for j in i + 1..bytes.len() {
                if bytes[j] == 'A' as u8 {
                    for k in j + 1..bytes.len() {
                        if bytes[k] == 'Q' as u8 {
                            ans += 1;
                        }
                    }
                }
            }
        }
    }
    writeln!(out, "{}", ans);
    // writeln!(out, "{}", "Hello Rust").unwrap();
}


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

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let w = i32::from_str(buf.trim()).unwrap();
    println!(
        "{}",
        match (w - 2) > 0 && (w - 2) % 2 == 0 {
            true => "YES",
            false => "NO",
        }
    )
}


use std::io;

fn main() {

    let mut weight = String::new();

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

    let trimmed = weight.trim();
    match trimmed.parse::<u8>() {
        Ok(i) => if i == 2 {
            println!("NO");
        } else if i%2 == 0 {
            println!("YES")
        }
        else {
            println!("NO")
        }
        Err(..) => println!("this was not an integer: {}", trimmed),
    }

}


use std::io;

fn main() {
    let mut n = String::new();
    io::stdin()
        .read_line(&mut n)
        .expect("Ошибка при чтении строки");
    let n: u32 = match n.trim().parse() {
        Ok(num) => num,
        Err(_) => return
    };
    match n % 2 == 0 && (n / 2) * 2 == n && n != 2 {
        true => println!("YES"),
        false => println!("NO")
    }
}


use std::io::BufRead;

fn main() {
    let n: i32 = std::io::stdin()
    .lock()
    .lines()
    .next()
    .expect("stdin should be available")
    .expect("couldn't read from stdin")
    .parse()
    .expect("input was not an integer");
    println!("{}", if n > 2 && n % 2 == 0 {
        "YES"
    } else {
        "NO"
    });
}


use std::io;

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

    io::stdin().read_line(&mut input).unwrap();
    let num: i8 = input.trim().parse().unwrap();
    watermelon(num);
}

fn watermelon(weight: i8) {
    if weight == 2 {
        println!("NO");
    } else if weight % 2 == 0 {
        println!("YES");
    } else {
        println!("NO");
    }
}


macro_rules! read {
	() => { read!("") };
	($msg:expr) => {{
		use std::io::Write;
		print!("{}", $msg);
		std::io::stdout().flush().unwrap();
		std::str::FromStr::from_str(&read_word()).unwrap()
	}};
}

pub fn read_word() -> String {
	use std::io::prelude::*;
	let mut word: Vec<u8> = vec![];

	for c in ::std::io::stdin().bytes() {
		let c = c.unwrap();
		if (c as char).is_whitespace() {
			if !word.is_empty() {
				break;
			}
		} else {
			word.push(c);
		}
	}
	::std::str::from_utf8(&word).unwrap().to_string()
}

fn main() {
	let w: i8 = read!();
	if w > 3 && w % 2 == 0 {
		println!("YES");
	} else {
		println!("NO");
	}
}


fn main() {
    let mut number_line = String::new();
    std::io::stdin().read_line(&mut number_line).unwrap();
    let number: i32 = number_line.trim().parse().unwrap();
    let result = if number == 2 || number % 2 != 0 {
        "NO"
    } else {
        "YES"
    };
    println!("{}", result);
}


//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_four_var<T: FromStr>() -> (T, T, 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(),*numbers.get(2).unwrap(),*numbers.get(3).unwrap() )

}
*/

fn main()  {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    let v: i32 =match line.trim().parse() {
        Ok(t) => t,
        Err(_e) => panic!()
    };
    if v%2 ==0 && v !=2{
        return println!("YES")
    }
    println!("NO")

}


use std::io;

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

fn main() {
    readln!();
    let encoded = readln!();
    let encoded: Vec<char> = encoded.chars().collect();

    let mut decoded = String::with_capacity(10);
    let mut index = 0;
    let mut decoded_index = 0;
    while index < encoded.len() {
        decoded.push(encoded[index]);
        decoded_index += 1;

        index += decoded_index;
    }

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


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 n: usize = scan.next();
    let arr: Vec<char> = scan.next::<String>().chars().collect();
    let mut res: Vec<char> = vec![];
    let mut i = 0usize;
    let mut cnt = 1usize;
    while i < n {
        res.push(arr[i]);
        i += cnt;
        cnt += 1;
    }
    let res: String = res.iter().collect();
    println!("{}", res);
}

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


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

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

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

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

use std::f64;

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

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

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

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

    //'outer: for _ in 0..t {
        let n:usize = read();
        let s:Vec<char> = read::<String>().chars().collect();

        let mut k = 1;
        let mut i = 0;
        while i < n {
            print!("{}", s[i]);
            i += k;
            k += 1;
        }
        println!();

    //}
}

/*

*/


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

fn decrypt(t: &str) -> String {
    let mut s = String::new();
    let mut step = 0;

    let mut iter = t.chars();
    while let Some(c) = iter.nth(step) {
        s.push(c);
        step += 1;
    }

    s
}

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

    let t = raw_input();
    print!("{}", decrypt(&t));
}


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

fn main() -> io::Result<()> {
    let stdin = io::stdin();
    let mut line_it = stdin.lock().lines();
    let n: usize = line_it.next().unwrap().unwrap().parse::<usize>().unwrap();
    let s: Vec<char> = line_it.next().unwrap().unwrap().chars().collect();
    let mut v: Vec<char> = Vec::new();
    let mut i = 0;
    let mut c = 1;
    while i < s.len() {
        v.push(s[i]);
        c += 1;
        i += c;
    }
    println!("{}", v.into_iter().collect::<String>());
    Ok(())
}


//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::io::*;
use std::str::*;
use std::fmt::Debug;
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).unwrap();
        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()
    }
}

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

    let n = input.u();
    let s = input.bs();
    let mut p = 0;
    for i in 1.. {
        print!("{}", s[p] as char);
        p += i;
        if p >= n {
            break;
        }
    }
}


use std::io;

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

    let mut line = String::new();
    stdin.read_line(&mut line).unwrap();
    let _m: usize = line.trim().parse().unwrap();

    let mut s = String::new();
    stdin.read_line(&mut s).unwrap();
    let s: Vec<char> = s.chars().collect();

    let mut res = String::new();
    let mut i: usize = 0;
    for delta in 1.. {
        if i >= s.len() {
            break;
        }
        res.push(s[i]);
        i += delta;
    }

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


fn main() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("INPUT::read line failed");
    let amount = input.trim().parse::<usize>().expect("LENGTH::parse to i32 failed");

    input.clear();

    std::io::stdin().read_line(&mut input).expect("INPUT::read line failed");
    let vec = input.chars().collect::<Vec<char>>();

    let mut index: usize = usize::default();
    let mut times: usize = usize::default();
    while index < amount {
        times += 1;
        print!("{}", &vec[index]);
        index += times;
    }
    println!();
}


#![allow(unused_imports)]
#![allow(unused_macros)]
// use proconio::input;
use std::cmp::{Ordering::*, Reverse};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, BufWriter, Write};
use std::str::{self, SplitAsciiWhitespace};

// I have no idea what I'm doing

macro_rules! answer {
    ($out:ident, $ans:expr) => {
        writeln!($out, "{}", $ans)
    };
}

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 s: String = scan.token();
    let mut s = s.chars();

    answer!(out, "hello".chars().all(|c| s.any(|x| c == x)).yes())
}

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

/// Mostly 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 [Scanner]");
            }
            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())
    }
}

// aka #![feature(bool_to_option)]
trait BoolThen {
    fn then_<T>(self, f: impl FnOnce() -> T) -> Option<T>;
}

impl BoolThen for bool {
    fn then_<T>(self, f: impl FnOnce() -> T) -> Option<T> {
        if self {
            Some(f())
        } else {
            None
        }
    }
}

trait BoolToYes {
    fn yes(self) -> &'static str;
}

impl BoolToYes for bool {
    fn yes(self) -> &'static str {
        match self {
            true => "YES",
            false => "NO",
        }
    }
}


use std::io;

fn main() {
    let list=input();
    let hello:Vec<&str>=vec!["h","e","l","l","o"];
    let mut i_hello=0;
    for i in &list{
        if i==hello[i_hello as usize]{
            i_hello+=1;
            if i_hello==5{
                break;
            }
        }
    }if i_hello==5{
        println!("YES");
    }else{
        println!("NO");
    }
}

fn read() -> String{
    let mut input=String::new();
    io::stdin().read_line(&mut input).expect("unable to read");
    input.trim().to_string()
}

fn input() -> Vec<String>{
    let inp:Vec<String>=read()
    .chars().map(|x| x.to_string()).collect();
    inp
}
/*  let n=read().parse::<i32>().expect("Failed to parse");
    let inp=read();
    (n,inp.split_whitespace().map(|x| x.parse::<i32>().expect("Failed to parse")).collect())
    let list: Vec<_>=inp.split_whitespace().collect();
    let qu: Vec<_>=read().chars().collect();
    (list[0].parse::<i32>().expect("Failed to parse"),
    list[1].parse::<i32>().expect("Failed to parse"),qu)
*/


use std::io::{BufWriter, stdin, stdout, 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 out = &mut BufWriter::new(stdout());

	let s = scan.next::<String>();

    let orig = "hello".as_bytes();
    let mut res = false;
    let mut i: usize = 0;

    for &c in s.as_bytes() {
        if c == orig[i] {
            i = i + 1;
            if i == orig.len() {
                res = true;
                break;
            }
        }
    }

    writeln!(out, "{}", if res { "YES" } else { "NO" }).expect("fail");
}


fn main(){
    let mut line=String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    let control=['h','e','l','l','o'];
    let mut line:Vec<char>=line
        .trim()
        .chars()
        .filter(|c|match c{
            'h'=>true,
            'e'=>true,
            'l'=>true,
            'o'=>true,
            _=>false,
        })
        .collect();
    line.push(' ');
    let len=line.len();
    let mut stop:usize=0;
    'control:for c in 0..5{
                for l in stop..=len{
                    if control[c]==line[l]{
                        stop=l+1;
                        continue'control
                    }
                    if c<5 && l==len-1{print!("NO");return}
                }
            }
    print!("YES")
}


use std::io;

fn substring(sentence: &str, word: &str) -> bool {
	if word.len() == 0 {
		return true;
	}
	else if sentence.len() == 0 {
		return false;
	}
	if sentence.chars().next() == word.chars().next() {
		return substring(&sentence[1..], &word[1..]);
	}
	else {
		return substring(&sentence[1..], &word[0..]);
	}
}

fn main() {
	let mut sentence = String::new();
	match io::stdin().read_line(&mut sentence) {
	    Ok(_) => (),
	    Err(e) => println!("Error: {}", e),
	}
	let word = "hello";
	println!("{}", if substring(&sentence, &word) {"YES"} else {"NO"});
}


fn main(){
    let a = vec!('h','e','l','l','o');
    let mut z = 0;
    let mut val = String::new();
    std::io::stdin().read_line(&mut val).unwrap();
    let val = val.trim().parse::<String>().unwrap();
    for j in val.chars(){
        if a[z] == j {
            z += 1;
        }
        if z == 5 {
            break;
        }
    }
    if z == 5{
        println!("YES");
    }
    else{
        println!("NO");
    }
}


fn main() {
    let mut text = String::new();
    std::io::stdin().read_line(&mut text).expect("");
    let mut hello = "hello".chars().peekable();
    for x in text.trim().chars() {
        if Some(&x) == hello.peek() {
            hello.next();
        }
    }
    println!("{}", if hello.peek() == None { "YES" } else { "NO" } );
}


use std::io::*;

fn read<T: std::str::FromStr>(i: &mut StdinLock) -> T {
    let mut s = String::new();
    i.by_ref().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn main() {
    // initialize stdin
    let sin = std::io::stdin();
    let mut sin = sin.lock();
    let sin = &mut sin;

    let input: String = read(sin);
    let target = ['h', 'e', 'l', 'l', 'o'];
    let mut current_idx = 0;

    for c in input.as_str().chars() {
        if c == target[current_idx as usize] {
            current_idx += 1;
            if current_idx == 5 {
                println!("YES");
                return;
            }
        }
    }
    println!("NO");
}


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 gcd(a: usize, b: usize) -> usize {
    let mut x = a;
    let mut y = b;
    let mut tmp = 0usize;
    while x > 0 {
        tmp = x;
        x = y % x;
        y = tmp;
    }
    y
}

fn _main() {
    let mut scan = Scan::new();
    let a: usize = scan.next();
    let b: usize = scan.next();
    let c: usize = scan.next();
    let d: usize = scan.next();
    let mut p = 0usize;
    let mut q = 0usize;
    if a * d >= c * b {
        p = c * b;
        q = a * d;
    } else {
        p = d * a;
        q = b * c;
    }
    p = q - p;
    let m = gcd(p, q);
    p = p / m;
    q = q / m;
    println!("{}/{}", p, q);
}

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

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

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

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

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

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

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


use std::io::{self, prelude::*, StdinLock, StdoutLock};
use std::str;

const MOD: u64 = 1e9 as u64 + 7;

fn solve(scan: &mut Scanner<StdinLock>, out: &mut io::BufWriter<StdoutLock>) {
    let n: u64 = scan.token();
    let k: u16 = scan.token();

    let mut ans = 1u64;
    for _ in 0..k {
        ans = (ans * n) % MOD;
    }
    writeln!(out, "{}", ans).ok();
}

struct Scanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: str::SplitWhitespace<'static>,
}

impl<R: 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 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_whitespace())
            }
        }
    }
}

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

    let t = scan.token::<usize>();
    for _ in 0..t {
        solve(&mut scan, &mut out);
    }
}


// ---------- begin scannner ----------
#[allow(dead_code)]
mod scanner {
	use std::str::FromStr;
	pub struct Scanner<'a> {
		it: std::str::SplitWhitespace<'a>,
	}
	impl<'a> Scanner<'a> {
		pub fn new(s: &'a String) -> Scanner<'a> {
			Scanner {
				it: s.split_whitespace(),
			}
		}
		pub fn next<T: FromStr>(&mut self) -> T {
			self.it.next().unwrap().parse::<T>().ok().unwrap()
		}
		pub fn next_bytes(&mut self) -> Vec<u8> {
			self.it.next().unwrap().bytes().collect()
		}
		pub fn next_chars(&mut self) -> Vec<char> {
			self.it.next().unwrap().chars().collect()
		}
		pub fn next_vec<T: FromStr>(&mut self, len: usize) -> Vec<T> {
			(0..len).map(|_| self.next()).collect()
		}
	}
}
// ---------- end scannner ----------
use std::io::Write;
fn main() {
	use std::io::Read;
	let mut s = String::new();
	std::io::stdin().read_to_string(&mut s).unwrap();
	let mut sc = scanner::Scanner::new(&s);
	let out = std::io::stdout();
	let mut out = std::io::BufWriter::new(out.lock());
	let t: usize = sc.next();
	for _ in 0..t {
		solve(&mut sc, &mut out);
	}
}
fn binary_exponentiation(a: i64, b: u64, mod_: i64) -> i64 {
	let mut ans: i64 = 1;
	let mut a = a % mod_;
	let mut b = b;
	while b != 0 {
		if (b & 1) == 1 {
			ans = ans * a % mod_;
		}
		a = a * a % mod_;
		b >>= 1;
	}
	return ans;
}
fn solve<W: Write>(sc: &mut scanner::Scanner, out: &mut std::io::BufWriter<W>) {
	let (n, k): (i64, u64) = (sc.next(), sc.next());
	let ans = binary_exponentiation(n, k, 1e9 as i64 + 7);
	writeln!(out, "{}", ans).ok();
}