There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of numbers l, l + 1, l + 2, ..., r; let's consider all its k-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one.Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where F1 = 1, F2 = 1, Fn = Fn - 1 + Fn - 2 for n ≥ 3.Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by m.

The first line contains four space-separated integers m, l, r and k (1 ≤ m ≤ 109; 1 ≤ l < r ≤ 1012; 2 ≤ k ≤ r - l + 1). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Print a single integer — the residue from dividing the sought greatest common divisor by m.

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

// Mint (mod any) {{{
#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] struct Mint(i32,i32);
#[allow(dead_code)] impl Mint {
	fn new<T: Copy+Into<i64>>(a: T, m: T) -> Self { Self(Self::cv(a,m),m.into() as i32) }
	unsafe fn new_unchecked(a: i32, m: i32) -> Self { Self(a,m) }
	fn hi(mut a: i32, m: i32) -> i32 { if a >= m { a -= m; } a }
	fn lo(mut a: i32, m: i32) -> i32 { if a < 0 { a += m; } a }
	fn cv<T: Copy+Into<i64>>(a: T, m: T) -> i32 { Self::lo((a.into() % m.into()) as i32, m.into() as i32) }
	unsafe fn inv(self) -> Self { self.pow(self.1-2) } // ONLY FOR PRIMES!
	fn pow<T: Copy+Into<i64>>(self, b: T) -> Self {
		let b = b.into(); if b == 0 { Self(1,self.1) } else {
			let mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res
		}
	}
}
impl Add for Mint { type Output = Self; fn add(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::hi(self.0 + a.0, self.1), self.1) }}
impl Sub for Mint { type Output = Self; fn sub(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::lo(self.0 - a.0, self.1), self.1) }}
impl Mul for Mint { type Output = Self; fn mul(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::cv(self.0 as i64 * a.0 as i64, self.1 as i64), self.1) }}
impl Div for Mint { type Output = Self; fn div(self, a: Self) -> Self::Output { self * unsafe {a.inv()} }}
impl Neg for Mint { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0, self.1), self.1) }}
impl AddAssign for Mint { fn add_assign(&mut self, a: Self) { *self = *self + a; } }
impl SubAssign for Mint { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }
impl MulAssign for Mint { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }
impl DivAssign for Mint { fn div_assign(&mut self, a: Self) { *self = *self / a; } }
use std::fmt::{Display, Formatter, Result};
impl Display for Mint { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.0) } }
//}}}

// Square Matrix {{{
type MatT = Mint;
#[derive(Debug,Clone)] struct Mat { n: usize, a: Vec<MatT>, v0: MatT, v1: MatT }
#[allow(dead_code)] impl Mat {
	fn new(n:usize,v0:MatT,v1:MatT)->Self{Self{n,a:vec![v0;n*n],v0,v1}}
	fn diag(n:usize,v0:MatT,v1:MatT,v:MatT)->Self{let mut m=Self::new(n,v0,v1);let mut p=0;for _ in 0..n{m.a[p]=v;p+=n+1;}m}
	fn pow(&self,n:u64)->Self{if n==0{Self::diag(self.n,self.v0,self.v1,self.v1)}else{let mut t=self.pow(n/2);t*=t.clone();if n%2==1{t*=self.clone();}t}}
	fn range(&self,r:Range<usize>,c:Range<usize>)->Vec<Vec<MatT>>{if r.start<r.end||c.start<c.end{Vec::new()}else{let mut res=vec![vec![self.v0;c.end-c.start];r.end-r.start];
		for i in r.start..r.end{let ir=i-r.start;let ii=i*self.n+c.start;for j in 0..c.end-c.start{res[ir][j]=self.a[ii+j];}}res}}
	fn at(&self,r:usize,c:usize)->MatT{self.a[r*self.n+c]}
	fn at_mut<'a>(&'a mut self,r:usize,c:usize)->&'a mut MatT{&mut self.a[r*self.n+c]}//'
}
impl Mul for Mat{type Output=Self;fn mul(self,o:Self)->Self::Output{assert!(self.n==o.n);let n=self.n;let mut res=Self::new(n,self.v0,self.v1);
	for ii in(0..n).map(|i|i*n){for j in 0..n{let mut t=self.v0;let mut kk=j;for k in 0..n{t+=self.a[ii+k]*o.a[kk];kk+=n;}res.a[ii+j]=t;}}res}}
impl Add for Mat{type Output=Self;fn add(mut self,o:Self)->Self{self+=o;self}}
impl Sub for Mat{type Output=Self;fn sub(mut self,o:Self)->Self{self-=o;self}}
impl MulAssign for Mat{fn mul_assign(&mut self,a:Self){*self=self.clone()*a;}}
impl AddAssign for Mat{fn add_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x+=y;}} }
impl SubAssign for Mat{fn sub_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x-=y;}} }
impl PartialEq for Mat{fn eq(&self,o:&Self)->bool{self.n==o.n&&self.a==o.a}}impl Eq for Mat{}
// }}}

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

	l!(m,l,r,k = rin.l());
	if m == 1 {
		writeln!(rout, "0").ok();
		return;
	}
	let g = || -> i64 {
		let mut a = Vec::new();
		for d in 1.. {
			if d*d > r { break; }
			a.push(d);
			a.push(r/d);
			a.push(l/d);
		}
		a.sort();
		a.dedup();
		a.reverse();
		for d in a {
			if r / d - (l-1) / d >= k {
				return d;
			}
		}
		panic!("no")
	}();
	let f1 = Mint::new(1,m);
	let f0 = Mint::new(0,m);
	let mut mat = Mat::new(2,f0,f1);
	*mat.at_mut(0,0) = f0;
	*mat.at_mut(0,1) = f1;
	*mat.at_mut(1,0) = f1;
	*mat.at_mut(1,1) = f1;
	let sol = mat.pow(g as u64).at(0,1);
	writeln!(rout, "{}", sol).ok();
}


This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each.As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball.The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies?Polycarp can throw his fire ball into an archer if the latter is already killed.

The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has.

In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.

use std::io::{self, BufReader, Read, Stdin, Bytes};
use std::fmt::Debug;
use std::cmp;
use std::str::FromStr;

/// A stdin helper to deal with normal oj input.
pub struct OjReader<R> {
    bs: Bytes<BufReader<R>>,
}

pub fn from_stdin() -> OjReader<Stdin> {
    let input = io::stdin();
    let reader = BufReader::new(input);
    OjReader { bs: reader.bytes() }
}

impl<R: Read> OjReader<R> {
    pub fn next<E, T>(&mut self) -> T
        where E: Debug,
              T: FromStr<Err = E>
    {
        loop {
            match self.next_opt() {
                Some(t) => return t,
                None => {},
            }
        }
    }

    pub fn next_opt<E, T>(&mut self) -> Option<T>
        where E: Debug,
              T: FromStr<Err = E>
    {
        self.next_trunk(|b| b == b' ' || b == b'\t' || b == b'\n' || b == b'\r')
    }

    // TODO: handle windows style line seperator \r\n
    fn next_trunk<E, T, F>(&mut self, is_sep: F) -> Option<T>
        where E: Debug,
              T: FromStr<Err = E>,
              F: Fn(u8) -> bool
    {
        let mut res = vec![];
        loop {
            match self.bs.next() {
                None => {
                    assert!(!res.is_empty());
                    break;
                },
                Some(r) => {
                    let b = r.unwrap();
                    if is_sep(b) {
                        break;
                    }
                    res.push(b);
                }
            }
        }
        if res.is_empty() {
            return None;
        }
        unsafe { Some(String::from_utf8_unchecked(res).parse::<T>().unwrap()) }
    }

    pub fn next_line(&mut self) -> String {
        self.next_line_opt().unwrap()
    }

    pub fn next_line_opt(&mut self) -> Option<String> {
        self.next_trunk(|b| b == b'\n' || b == b'\r')
    }
}

macro_rules! odiv {
    ($lhs:expr, $rhs:expr) => ({
        if $lhs < 0 {
            0
        } else {
            $lhs / $rhs + 1
        }
    });
}

#[derive(Debug)]
struct Problem {
    a: isize,
    b: isize,
    thls: Vec<isize>,
}

fn search(p: &mut Problem, i: usize, tmp_sol: &mut Vec<usize>, sol: &mut Vec<usize>) {
    assert!(i > 0);
    if i == p.thls.len() - 2 {
        let res = cmp::max(odiv!(p.thls[i], p.a), odiv!(cmp::max(p.thls[i - 1], p.thls[i + 1]), p.b)) as usize;
        if !sol.is_empty() && sol.len() <= tmp_sol.len() + res {
            return;
        }
        *sol = tmp_sol.clone();
        for _ in 0..res {
            sol.push(i + 1);
        }
    } else if i < p.thls.len() - 2 {
        let min = odiv!(p.thls[i - 1], p.b) as usize;
        let max = cmp::max(odiv!(p.thls[i], p.a), odiv!(p.thls[i + 1], p.b)) as usize;
        let (old_one, old_two, last_moves) = (p.thls[i], p.thls[i + 1], tmp_sol.len());
        p.thls[i] -= p.a * min as isize;
        p.thls[i + 1] -= p.b * min as isize;
        tmp_sol.resize(last_moves + min, i + 1);
        for _ in min..cmp::max(min + 1, max + 1) {
            search(p, i + 1, tmp_sol, sol);
            p.thls[i] -= p.a;
            p.thls[i + 1] -= p.b;
            tmp_sol.push(i + 1);
            if tmp_sol.len() > sol.len() {
                break;
            }
        }
        p.thls[i] = old_one;
        p.thls[i + 1] = old_two;
        tmp_sol.truncate(last_moves);
    } else {
        unreachable!();
    }
}

// Simple a + b example
fn main() {
    let mut reader = from_stdin();
    let (n, a, b) = (reader.next(), reader.next(), reader.next());
    let mut problem = Problem {
        a: a,
        b: b,
        thls: Vec::with_capacity(n),
    };
    for _ in 0..n {
        problem.thls.push(reader.next());
    }
    let (mut tmp_sol, mut sol) = (vec![], vec![]);
    search(&mut problem, 1, &mut tmp_sol, &mut sol);
    println!("{}", sol.len());
    for idx in sol {
        print!("{} ", idx);
    }
    print!("\n");
}


There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.  King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.

The first line contains number n, which is the number of knights at the round table (3 ≤ n ≤ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.

Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".

use std::io::{self, BufWriter, Write};
use std::str::{self, SplitAsciiWhitespace};

// I have no idea what I'm doing

struct It {
    x: usize,
    n: usize,
    mark: Vec<bool>,
}

// 4 is prime
fn primes_that_divide(n: usize) -> It {
    It {
        x: 3,
        n: n,
        mark: vec![false; n + 1],
    }
}

impl Iterator for It {
    type Item = usize;
    fn next(&mut self) -> Option<Self::Item> {
        while self.x <= self.n {
            if self.mark[self.x] {
                self.x += 1;
                continue;
            }

            for y in self.mark.iter_mut().skip(self.x).step_by(self.x) {
                *y = true;
            }

            if self.n % self.x == 0 {
                self.x += 1;
                return Some(self.x - 1);
            }

            self.x += 1;
        }

        None
    }
}

fn is_lucky(n: usize, mood: &[bool], p: usize) -> bool {
    let step = n / p;
    (0..step).any(|start|
        (start..n).step_by(step).all(|i| mood[i]))
}

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: usize = scan.token();
    let mood: Vec<_> = (0..n).map(|_| scan.token::<char>()).map(|c| c == '1').collect();

    let ans = primes_that_divide(n)
                .any(|p| is_lucky(n, &mood, p));

    writeln!(out, "{}", match ans {
        true => "YES",
        false => "NO",
    })?;

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


Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?

The first line contains the only integer n (0≤n≤10^100000). It is guaranteed that n doesn't contain any leading zeroes.

Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.

In the first sample the number already is one-digit — Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991→19→10→1. After three transformations the number becomes one-digit.

import std.stdio;
import std.conv;

int sumit(string str) {
    int result = 0;
    foreach (c; str) {
        result += c - '0';
    }
    return result;
}

int main() {
    debug stdin = File("in.txt", "r");

    string str;
    readf(" %s\n", &str);
    int answer = 0;
    while (str.length > 1) {
        ++answer;
        int res = sumit(str);
        str = to!string(res);
    }
    writeln(answer);

    return 0;
}


There are $$$n$$$ benches in the Berland Central park. It is known that $$$a_i$$$ people are currently sitting on the $$$i$$$-th bench. Another $$$m$$$ people are coming to the park and each of them is going to have a seat on some bench out of $$$n$$$ available.Let $$$k$$$ be the maximum number of people sitting on one bench after additional $$$m$$$ people came to the park. Calculate the minimum possible $$$k$$$ and the maximum possible $$$k$$$.Nobody leaves the taken seat during the whole process.

The first line contains a single integer $$$n$$$ $$$(1 \\le n \\le 100)$$$ — the number of benches in the park.
The second line contains a single integer $$$m$$$ $$$(1 \\le m \\le 10\\,000)$$$ — the number of people additionally coming to the park.
Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ $$$(1 \\le a_i \\le 100)$$$ — the initial number of people on the $$$i$$$-th bench.

Print the minimum possible $$$k$$$ and the maximum possible $$$k$$$, where $$$k$$$ is the maximum number of people sitting on one bench after additional $$$m$$$ people came to the park.

In the first example, each of four benches is occupied by a single person. The minimum $$$k$$$ is $$$3$$$. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum $$$k$$$ is $$$7$$$. That requires all six new people to occupy the same bench.
The second example has its minimum $$$k$$$ equal to $$$15$$$ and maximum $$$k$$$ equal to $$$15$$$, as there is just a single bench in the park and all $$$10$$$ people will occupy it.

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n, m; rd(n); rd(m);
  auto a=new int[](n);
  foreach(i; 0..n) rd(a[i]);

  auto mx=reduce!(max)(a);
  int sub=0;
  foreach(e; a) sub+=(mx-e);
  if(m<=sub){
    writeln(mx, " ", mx+m);
    return;
  }
  auto k2=mx+m;
  m-=sub;
  writeln(mx+(m+n-1)/n, " ", k2);

}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.

The only line contains an integer n (1≤n≤10^18).
Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

Print on the single line "YES" if n is a nearly lucky number. Otherwise, print "NO" (without the quotes).

In the first sample there are 3 lucky digits (first one and last two), so the answer is "NO".
In the second sample there are 7 lucky digits, 7 is lucky number, so the answer is "YES".
In the third sample there are no lucky digits, so the answer is "NO".

import std;

void main() {
    string n;
    readf("%s\n", n);

    ulong cnt = n.count('4') + n.count('7');

    bool isNearlyLucky = (cnt > 0);
    while (cnt > 0) {
        ulong d = cnt % 10;
        isNearlyLucky &= (d == 4 || d == 7);

        cnt /= 10;
    }

    writeln(isNearlyLucky ? "YES" : "NO");
}


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3,10 d: 4,8 e: 6 f: 7 z: 1,5,9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5-1=4, 9-5=4, for letters c: 10-3=7, for letters d: 8-4=4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.

The single line contains a positive integer n (1≤n≤10^5) — the length of the sought string.

Print on the single line the lexicographically minimal lucky string whose length equals n.

The lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1≤i≤n), that ai<bi, and for any j (1≤j<i) aj=bj.

import std.stdio, std.string, std.conv;
import std.algorithm, std.array, std.bigint, std.math, std.range;
import core.thread;

//  Input
string[] tokens;
int tokenId = 0;
string readToken() { for (; tokenId == tokens.length; ) tokens = readln.split, tokenId = 0; return tokens[tokenId++]; }

int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

//  chmin/chmax
void chmin(T)(ref T t, T f) { if (t > f) t = f; }
void chmax(T)(ref T t, T f) { if (t < f) t = f; }

int N;
string source = "abcd";

void main () {
    N = readInt();

    foreach (int i; 0 .. N) {
        writef("%s", source[i % 4]);
    }
    writeln("");
}

[{'input': ['5\r\n'], 'output': ['abcda\r\n']}, {'input': ['3\r\n'], 'output': ['abc\r\n']}, {'input': ['8\r\n'], 'output': ['abcdabcd\r\n']}, {'input': ['10\r\n'], 'output': ['abcdabcdab\r\n']}, {'input': ['16\r\n'], 'output': ['abcdabcdabcdabcd\r\n']}, {'input': ['64\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd\r\n']}, {'input': ['128\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd\r\n']}, {'input': ['100\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd\r\n']}, {'input': ['47\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabc\r\n']}, {'input': ['74\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdab\r\n']}, {'input': ['477\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcda\r\n']}, {'input': ['1\r\n'], 'output': ['a\r\n']}, {'input': ['2\r\n'], 'output': ['ab\r\n']}, {'input': ['7\r\n'], 'output': ['abcdabc\r\n']}, {'input': ['4\r\n'], 'output': ['abcd\r\n']}, {'input': ['99\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabc\r\n']}, {'input': ['6\r\n'], 'output': ['abcdab\r\n']}, {'input': ['9\r\n'], 'output': ['abcdabcda\r\n']}]


Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.

The first line contains two integers n and k (2≤n≤100, 1≤k≤1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai — integers xi and yi, separated by a space.
All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.

Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10^-6.

import std.stdio;
import std.math;

void main() {
    int n, k; scanf("%u %u", &n, &k);
    double t = 0;
    double x, y, px, py;
    scanf("%lf %lf", &px, &py);
    foreach (i; 1 .. n) {
        scanf("%lf %lf", &x, &y);
        double dx = abs(x - px);
        double dy = abs(y - py);
        t += sqrt(dx * dx + dy * dy);
        px = x; py = y;
    }
    printf("%.9f\n", t / 50 * k);
}


HQ9+ is a joke programming language which has only four one-character instructions: "H" prints "Hello, World!", "Q" prints the source code of the program itself, "9" prints the lyrics of "99 Bottles of Beer" song,  "+" increments the value stored in the internal accumulator.Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.

The input will consist of a single line p which will give a program in HQ9+. String p will contain between 1 and 100 characters, inclusive. ASCII-code of each character of p will be between 33 (exclamation mark) and 126 (tilde), inclusive.

Output "YES", if executing the program will produce any output, and "NO" otherwise.

In the first case the program contains only one instruction — "H", which prints "Hello, World!".
In the second case none of the program characters are language instructions.

import std;

void main() {
    string p;
    readf("%s\n", p);

    bool isOK;
    foreach (x; p) {
        isOK |= (x == 'H' || x == 'Q' || x == '9');
    }

    writeln(isOK ? "YES" : "NO");
}

[{'input': ['Hi!\r\n'], 'output': ['YES\r\n']}, {'input': ['Codeforces\r\n'], 'output': ['NO\r\n']}, {'input': ['a+b=c\r\n'], 'output': ['NO\r\n']}, {'input': ['hq-lowercase\r\n'], 'output': ['NO\r\n']}, {'input': ['Q\r\n'], 'output': ['YES\r\n']}, {'input': ['9\r\n'], 'output': ['YES\r\n']}, {'input': ['H\r\n'], 'output': ['YES\r\n']}, {'input': ['+\r\n'], 'output': ['NO\r\n']}, {'input': ['~\r\n'], 'output': ['NO\r\n']}, {'input': ['dEHsbM\'gS[\\brZ_dpjXw8f?L[4E"s4Zc9*(,j:>p$}m7HD[_9nOWQ\\uvq2mHWR\r\n'], 'output': ['YES\r\n']}, {'input': ['tt6l=RHOfStm.;Qd$-}zDes*E,.F7qn5-b%HC\r\n'], 'output': ['YES\r\n']}, {'input': ['@F%K2=%RyL/\r\n'], 'output': ['NO\r\n']}, {'input': ['juq)k(FT.^G=G\\zcqnO"uJIE1_]KFH9S=1c"mJ;F9F)%>&.WOdp09+k`Yc6}"6xw,Aos:M\\_^^:xBb[CcsHm?J\r\n'], 'output': ['YES\r\n']}, {'input': ['6G_"Fq#<AWyHG=Rci1t%#Jc#x<Fpg\'N@t%F=``YO7\\Zd;6PkMe<#91YgzTC)\r\n'], 'output': ['YES\r\n']}, {'input': ['Fvg_~wC>SO4lF}*c`Q;mII9E{4.QodbqN]C\r\n'], 'output': ['YES\r\n']}, {'input': ['p-UXsbd&f\r\n'], 'output': ['NO\r\n']}, {'input': ['<]D7NMA)yZe=`?RbP5lsa.l_Mg^V:"-0x+$3c,q&L%18Ku<HcA\\s!^OQblk^x{35S\'>yz8cKgVHWZ]kV0>_\r\n'], 'output': ['YES\r\n']}, {'input': ['f.20)8b+.R}Gy!DbHU3v(.(=Q^`z[_BaQ}eO=C1IK;b2GkD\\{\\Bf"!#qh]\r\n'], 'output': ['YES\r\n']}, {'input': ['}do5RU<(w<q["-NR)IAH_HyiD{\r\n'], 'output': ['YES\r\n']}, {'input': ["Iy^.,Aw*,5+f;l@Q;jLK'G5H-r1Pfmx?ei~`CjMmUe{K:lS9cu4ay8rqRh-W?Gqv!e-j*U)!Mzn{E8B6%~aSZ~iQ_QwlC9_cX(o8\r\n"], 'output': ['YES\r\n']}, {'input': ['sKLje,:q>-D,;NvQ3,qN3-N&tPx0nL/,>Ca|z"k2S{NF7btLa3_TyXG4XZ:`(t&"\'^M|@qObZxv\r\n'], 'output': ['YES\r\n']}, {'input': ['%z:c@1ZsQ@\\6U/NQ+M9R>,$bwG`U1+C\\18^:S},;kw!&4r|z`\r\n'], 'output': ['YES\r\n']}, {'input': ['OKBB5z7ud81[Tn@P"nDUd,>@\r\n'], 'output': ['NO\r\n']}, {'input': ["y{0;neX]w0IenPvPx0iXp+X|IzLZZaRzBJ>q~LhMhD$x-^GDwl;,a'<bAqH8QrFwbK@oi?I'W.bZ]MlIQ/x(0YzbTH^l.)]0Bv\r\n"], 'output': ['YES\r\n']}, {'input': ['EL|xIP5_+Caon1hPpQ0[8+r@LX4;b?gMy>;/WH)pf@Ur*TiXu*e}b-*%acUA~A?>MDz#!\\Uh\r\n'], 'output': ['YES\r\n']}, {'input': ['UbkW=UVb>;z6)p@Phr;^Dn.|5O{_i||:Rv|KJ_ay~V(S&Jp\r\n'], 'output': ['NO\r\n']}, {'input': ['!3YPv@2JQ44@)R2O_4`GO\r\n'], 'output': ['YES\r\n']}, {'input': ['Kba/Q,SL~FMd)3hOWU\'Jum{9"$Ld4:GW}D]%tr@G{hpG:PV5-c\'VIZ~m/6|3I?_4*1luKnOp`%p|0H{[|Y1A~4-ZdX,Rw2[\\\r\n'], 'output': ['YES\r\n']}, {'input': ['NRN*=v>;oU7[acMIJn*n^bWm!cm3#E7Efr>{g-8bl"DN4~_=f?[T;~Fq#&)aXq%</GcTJD^e$@Extm[e"C)q_L\r\n'], 'output': ['NO\r\n']}, {'input': ["y#<fv{_=$MP!{D%I\\1OqjaqKh[pqE$KvYL<9@*V'j8uH0/gQdA'G;&y4Cv6&\r\n"], 'output': ['YES\r\n']}, {'input': ['+SE_Pg<?7Fh,z&uITQut2a-mk8X8La`c2A}\r\n'], 'output': ['YES\r\n']}, {'input': ['Uh3>ER](J\r\n'], 'output': ['NO\r\n']}, {'input': ['!:!{~=9*\\P;Z6F?HC5GadFz)>k*=u|+"Cm]ICTmB!`L{&oS/z6b~#Snbp/^\\Q>XWU-vY+/dP.7S=-#&whS@,\r\n'], 'output': ['YES\r\n']}, {'input': ['KimtYBZp+ISeO(uH;UldoE6eAcp|9u?SzGZd6j-e}[}u#e[Cx8.qgY]$2!\r\n'], 'output': ['YES\r\n']}, {'input': ['[:[SN-{r>[l+OggH3v3g{EPC*@YBATT@\r\n'], 'output': ['YES\r\n']}, {'input': ["'jdL(vX\r\n"], 'output': ['NO\r\n']}, {'input': ['Q;R+aay]cL?Zh*uG"YcmO*@Dts*Gjp}D~M7Z96+<4?9I3aH~0qNdO(RmyRy=ci,s8qD_kwj;QHFzD|5,5\r\n'], 'output': ['YES\r\n']}, {'input': ['{Q@#<LU_v^qdh%gGxz*pu)Y"]k-l-N30WAxvp2IE3:jD0Wi4H/xWPH&s\r\n'], 'output': ['YES\r\n']}, {'input': ['~@Gb(S&N$mBuBUMAky-z^{5VwLNTzYg|ZUZncL@ahS?K*As<$iNUARM3r43J\'jJB)$ujfPAq"G<S9flGyakZg!2Z.-NJ|2{F>]\r\n'], 'output': ['YES\r\n']}, {'input': ['Jp5Aa>aP6fZ!\\6%A}<S}j{O4`C6y$8|i3IW,WHy&"ioE&7zP"\'xHAY;:x%@SnS]Mr{R|})gU\r\n'], 'output': ['YES\r\n']}, {'input': ['ZA#:U)$RI^sE\\vuAt]x"2zipI!}YEu2<j$:H0_9/~eB?#->\r\n'], 'output': ['YES\r\n']}, {'input': ['&ppw0._:\\p-PuWM@l}%%=\r\n'], 'output': ['NO\r\n']}, {'input': ['P(^pix"=oiEZu8?@d@J(I`Xp5TN^T3\\Z7P5"ZrvZ{2Fwz3g-8`U!)(1$a<g+9Q|COhDoH;HwFY02Pa|ZGp$/WZBR=>6Jg!yr\r\n'], 'output': ['YES\r\n']}, {'input': ['`WfODc\\?#ax~1xu@[ao+o_rN|L7%v,p,nDv>3+6cy.]q3)+A6b!q*Hc+#.t4f~vhUa~$^q\r\n'], 'output': ['YES\r\n']}, {'input': [",)TH9N}'6t2+0Yg?S#6/{_.,!)9d}h'wG|sY&'Ul4D0l0\r\n"], 'output': ['YES\r\n']}, {'input': ['VXB&r9Z)IlKOJ:??KDA\r\n'], 'output': ['YES\r\n']}, {'input': ['")1cL>{o\\dcYJzu?CefyN^bGRviOH&P7rJS3PT4:0V3F)%\\}L=AJouYsj_>j2|7^1NWu*%NbOP>ngv-ls<;b-4Sd3Na0R\r\n'], 'output': ['YES\r\n']}, {'input': ["2Y}\\A)>row{~c[g>:'.|ZC8%UTQ/jcdhK%6O)QRC.kd@%y}LJYk=V{G5pQK/yKJ%{G3C\r\n"], 'output': ['YES\r\n']}, {'input': ['O.&=qt(`z(\r\n'], 'output': ['NO\r\n']}, {'input': ['_^r6fyIc/~~;>l%9?aVEi7-{=,[<aMiB\'-scSg$$|"jAzY0N>QkHHGBZj2c"=fhRlWd5;5K|GgU?7h]!;wl@\r\n'], 'output': ['YES\r\n']}, {'input': ['+/`sAd&eB29E=Nu87${.u6GY@$^a$,}s^!p!F}B-z8<<wORb<S7;HM1a,gp\r\n'], 'output': ['YES\r\n']}, {'input': ['U_ilyOGMT+QiW/M8/D(1=6a7)_FA,h4`8\r\n'], 'output': ['YES\r\n']}, {'input': ['!0WKT:$O\r\n'], 'output': ['NO\r\n']}, {'input': ["1EE*I%EQz6$~pPu7|(r7nyPQt4uGU@]~H'4uII?b1_Wn)K?ZRHrr0z&Kr;}aO3<mN=3:{}QgPxI|Ncm4#)\r\n"], 'output': ['YES\r\n']}, {'input': ['[u3"$+!:/.<Dp1M7tH}:zxjt],^kv}qP;y12"`^\'/u*h%AFmPJ>e1#Yly\r\n'], 'output': ['YES\r\n']}, {'input': ["'F!_]tB<A&UO+p?7liE>(x&RFgG2~\\(\r\n"], 'output': ['NO\r\n']}, {'input': ['Qv)X8\r\n'], 'output': ['YES\r\n']}, {'input': ['aGv7,J@&g1(}E3g6[LuDZwZl2<v7IwQA%"R(?ouBD>_=y"3Kf%^>vON<a^T\\G^ootgE@whWmZo=[ex|F\r\n'], 'output': ['YES\r\n']}, {'input': ['e{}2vQ+/r@p0}cLKNe4MCk\r\n'], 'output': ['YES\r\n']}, {'input': ['mzbmweyydiadtlcouegmdbyfwurpwbpuvhifnuapwyndmhtqvkgkbhtytszotwflegsjzzszfwtzfpnscguemwrczqxycivdqnkH\r\n'], 'output': ['YES\r\n']}, {'input': ['Qzbmweyydiadtlcouegmdbyfwurpwbpuvhifnuapwyndmhtqvkgkbhtytszotwflegsjzzszfwtzfpnscguemwrczqxycivdqnky\r\n'], 'output': ['YES\r\n']}, {'input': ['mzbmweyydiadtlcouegmdbyfwurpwb9uvhifnuapwyndmhtqvkgkbhtytszotwflegsjzzszfwtzfpnscguemwrczqxycivdqnky\r\n'], 'output': ['YES\r\n']}, {'input': ['1H1\r\n'], 'output': ['YES\r\n']}, {'input': ['+Q\r\n'], 'output': ['YES\r\n']}, {'input': ['1ab\r\n'], 'output': ['NO\r\n']}, {'input': ['!\r\n'], 'output': ['NO\r\n']}, {'input': ['0+\r\n'], 'output': ['NO\r\n']}, {'input': ['+H\r\n'], 'output': ['YES\r\n']}, {'input': ['cH\r\n'], 'output': ['YES\r\n']}, {'input': ['+8\r\n'], 'output': ['NO\r\n']}, {'input': ['8+\r\n'], 'output': ['NO\r\n']}, {'input': ['++++++++++++++++++++++++++\r\n'], 'output': ['NO\r\n']}, {'input': ['(+)\r\n'], 'output': ['NO\r\n']}, {'input': ['H+\r\n'], 'output': ['YES\r\n']}, {'input': ['a!\r\n'], 'output': ['NO\r\n']}, {'input': ['++++++++++++++\r\n'], 'output': ['NO\r\n']}, {'input': ['+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n'], 'output': ['NO\r\n']}, {'input': ['8\r\n'], 'output': ['NO\r\n']}, {'input': ['3\r\n'], 'output': ['NO\r\n']}, {'input': ['HQ9\r\n'], 'output': ['YES\r\n']}, {'input': ['+++H\r\n'], 'output': ['YES\r\n']}, {'input': ['++++++++++\r\n'], 'output': ['NO\r\n']}, {'input': ['HHHHHHH\r\n'], 'output': ['YES\r\n']}, {'input': ['abacabaH\r\n'], 'output': ['YES\r\n']}, {'input': ['+G\r\n'], 'output': ['NO\r\n']}]


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1,a2,...,an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1≤n≤5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1≤ai≤5000,1≤i≤n).

Print the only number — the minimum number of changes needed to get the permutation.

The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2.

module cf_137B;

import std.stdio, std.algorithm;

void main() {
	int n;
	int[] numbers;

	readf("%d", &n);
	numbers = new int[n];
	for (auto i = 0; i < n; ++i) {
		readf(" %d", &numbers[i]);
	}

	sort(numbers);

	int skip = 0, index = 0;
	for (auto i = 1; i <= n; ++i) {
		if (index >= n) {
			++skip;
			continue;
		}

		if (numbers[index] == i) {
			while (index < n && numbers[index] == i) {
				++index;
			}
		} else {
			++skip;
		}
	}

	writeln(skip);
}


What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" — thought Petya. He know for a fact that if he fulfills the parents' task in the i-th (1≤i≤12) month of the year, then the flower will grow by ai centimeters, and if he doesn't water the flower in the i-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by k centimeters. Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by k centimeters.

The first line contains exactly one integer k (0≤k≤100). The next line contains twelve space-separated integers: the i-th (1≤i≤12) number in the line represents ai (0≤ai≤100).

Print the only integer — the minimum number of months when Petya has to water the flower so that the flower grows no less than by k centimeters. If the flower can't grow by k centimeters in a year, print -1.

Let's consider the first sample test. There it is enough to water the flower during the seventh and the ninth month. Then the flower grows by exactly five centimeters.
In the second sample Petya's parents will believe him even if the flower doesn't grow at all (k=0). So, it is possible for Petya not to water the flower at all.

import std;

void main() {
    int k;
    readf("%d\n", k);

    auto a = readln.chomp.split.to!(int[]);

    if (k == 0) {
        writeln(0);
        return;
    }

    a.sort!"a > b";

    foreach (i, x; a) {
        k -= x;
        if (k <= 0) {
            writeln(i+1);
            return;
        }
    }

    writeln(-1);
}


A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.

The first line of the input data contains numbers n and m (1≤n,m≤50), n — amount of lines, and m — amount of columns on Bob's sheet. The following n lines contain m characters each. Character «.» stands for a non-shaded square on the sheet, and «*» — for a shaded square. It is guaranteed that Bob has shaded at least one square.

Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better.

import std.algorithm, std.string, std.stdio, std.conv, std.range ;

void main()
{
    auto nm = readln.split.map!(to!int);
    auto n = nm[0], m = nm[1];
    auto lines  = n.iota.map!(_ => readln.chomp).array;
    lines = lines.strip!(a => a == repeat(".").take(lines[0].length).array.join(""));
    auto lines1 = lines[0].length.iota.array.map!(i => lines.transversal(i).array);
    auto lines2 = lines1.strip!(a => a == repeat(".").take(lines1[0].length).array.join(""));
    lines2[0].length.iota.array.map!(i => lines2.transversal(i).array).each!writeln;
}


Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj,bj) can close marker (xi,yi) only if their diameters match, that is, bj=yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj=xi.Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.

The first input line contains two space-separated integers n and m (1≤n,m≤10^5) — the number of markers and the number of caps, correspondingly.
Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1≤xi,yi≤1000) — the i-th marker's color and diameter, correspondingly.
Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1≤aj,bj≤1000) — the color and diameter of the j-th cap, correspondingly.

Print two space-separated integers u,v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.

In the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed — the first and the third markers.

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    auto ns = readln.chomp.split.map!(to!int).array;

    auto vals = new int[][][] (2, 1001, 1001);
    foreach (i; 0 .. 2) {
        foreach (_; 0 .. ns[i]) {
            int x, y;
            readf("%s %s", &x, &y);
            readln;
            vals[i][y][x] += 1;
        }
    }

    int u = 0, v = 0;
    foreach (d; 1 .. 1001) {
        int mleft = 0, cleft = 0;
        int ok = 0;
        foreach (c; 1 .. 1001) {
            ok += min(vals[0][d][c], vals[1][d][c]);
            if (vals[0][d][c] > vals[1][d][c]) mleft += vals[0][d][c] - vals[1][d][c];
            else cleft += vals[1][d][c] - vals[0][d][c];
        }

        u += ok;
        v += ok;

        u += min(mleft, cleft);
    }

    writeln(u, ' ', v);
}


You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (10^9+7).

The first line contains the only integer n (1≤n≤10^7) — the required length of the cyclic path.

Print the only integer — the required number of ways modulo 1000000007 (10^9+7).

The required paths in the first sample are:
  D-A-D  D-B-D  D-C-D

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio, std.bitmanip;

void main() {
    immutable int MOD = 10^^9+7;
    auto N = readln.chomp.to!int;

    auto dp = new long[][](2, 4);
    dp[0][0] = 1;
    dp[0][1] = dp[0][2] = dp[0][3] = 0;

    foreach (i; 0..N) {
        auto cur = i % 2;
        auto tar = 1 - cur;
        dp[tar][0] = (dp[cur][1] + dp[cur][2] + dp[cur][3]) % MOD;
        dp[tar][1] = (dp[cur][0] + dp[cur][2] + dp[cur][3]) % MOD;
        dp[tar][2] = (dp[cur][0] + dp[cur][1] + dp[cur][3]) % MOD;
        dp[tar][3] = (dp[cur][0] + dp[cur][1] + dp[cur][2]) % MOD;
    }

    writeln(dp[N%2][0]);
}


A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.

The first line of the input contains integer n (1≤n≤2·10^8) and integer m (1≤m≤20). The i+1-th line contains a pair of numbers ai and bi (1≤ai≤10^8,1≤bi≤10). All the input numbers are integer.

Output the only number — answer to the problem.

import std.conv, std.string, std.stdio, std.algorithm, std.typecons;

void main()
{
    auto nm = readln.split.map!(to!long);
    auto n = nm[0], m = nm[1];
    auto t = [tuple(0L,0L)];
    foreach(i; 0..m)
    {
        auto v = readln.split.map!(to!long);
        t ~= tuple(v[0],v[1]);
    }
    t.sort!"a[1]>b[1]";
    auto count = 0;
    for (auto i = 0, j = n; i < m && j > 0; i++ ) {
        if (j-t[i][0] >= 0)
            count += t[i][0] * t[i][1];
        else
            count += j * t[i][1];
        j-=t[i][0];
    }
    writeln(count);
}


A boy Valera registered on site Codeforces as Valera, and wrote his first Codeforces Round #300. He boasted to a friend Arkady about winning as much as x points for his first contest. But Arkady did not believe his friend's words and decided to check whether Valera could have shown such a result.He knows that the contest number 300 was unusual because there were only two problems. The contest lasted for t minutes, the minutes are numbered starting from zero. The first problem had the initial cost of a points, and every minute its cost reduced by da points. The second problem had the initial cost of b points, and every minute this cost reduced by db points. Thus, as soon as the zero minute of the contest is over, the first problem will cost a-da points, and the second problem will cost b-db points. It is guaranteed that at any moment of the contest each problem has a non-negative cost.Arkady asks you to find out whether Valera could have got exactly x points for this contest. You should assume that Valera could have solved any number of the offered problems. You should also assume that for each problem Valera made no more than one attempt, besides, he could have submitted both problems at the same minute of the contest, starting with minute 0 and ending with minute number t-1. Please note that Valera can't submit a solution exactly t minutes after the start of the contest or later.

The single line of the input contains six integers x,t,a,b,da,db (0≤x≤600; 1≤t,a,b,da,db≤300) — Valera's result, the contest's duration, the initial cost of the first problem, the initial cost of the second problem, the number of points that the first and the second problem lose per minute, correspondingly.
It is guaranteed that at each minute of the contest each problem has a non-negative cost, that is, a-i·da≥0 and b-i·db≥0 for all 0≤i≤t-1.

If Valera could have earned exactly x points at a contest, print "YES", otherwise print "NO" (without the quotes).

In the first sample Valera could have acted like this: he could have submitted the first problem at minute 0 and the second problem — at minute 2. Then the first problem brings him 20 points and the second problem brings him 10 points, that in total gives the required 30 points.

module cf_203A;

import std.stdio;

void main() {
    int x, t, a, b, da, db;

    readf("%d %d %d %d %d %d", &x, &t, &a, &b, &da, &db);

    bool valeraSaidTrue = false;
    int aa = a;

    dualFor:
    for (int i = 0; i <= t; ++i) {
        int bb = b;

        if (i == t) {
            aa = 0;
        }
        for (int j = 0; j <= t; ++j) {
            if (j == t) {
                bb = 0;
            }
            if (aa + bb == x) {
                valeraSaidTrue = true;
                break dualFor;
            }
            bb -= db;
        }
        aa -= da;
    }

    writeln(valeraSaidTrue? "YES": "NO");
}


Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1≤n≤100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1≤xi,yi≤1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

import std.stdio, std.string, std.conv, std.range, std.array, std.algorithm;
import std.uni, std.math, std.container, std.typecons, std.typetuple;
import core.bitop, std.datetime;

immutable int mod = 10^^9 + 7;

void main(){
    int n = readln.chomp.to!int;

    auto x = new int[](n);
    auto y = new int[](n);

    foreach(i ; 0 .. n){
        readVars(x[i], y[i]);
    }

    auto visited = new bool[](n);

    int ans;

    foreach(i ; 0 .. n){
        if(!visited[i]){
            dfs(n, x, y, visited, i);
            ans++;
        }
    }

    writeln(ans - 1);
}

void dfs(int n, int[] x, int[] y, bool[] visited, int i) {
    visited[i] = true;

    foreach(j ; 0 .. n){
        if((x[j] == x[i] || y[j] == y[i]) && !visited[j]){
            dfs(n, x, y, visited, j);
        }
    }
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}


Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.

The first line contains two integers n, m (1≤n,m≤10^5). The next n lines contain pairs of integers. The i-th line contains integers ci,ti (1≤ci,ti≤10^9) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 10^9 .
The next line contains m positive integers v1,v2,...,vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi<vi+1 (i<m).
The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.

Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto C = new int[N],
         T = new int[N];
    foreach (i; 0 .. N) {
        int c, t; scanf("%d %d\n", &c, &t);
        C[i] = c;
        T[i] = t;
    }
    auto qs = readln.chomp.split(" ").map!(to!int).array;

    int cur_time = 0;
    int index = 0;
    foreach (q; qs) {
first:;
        if (cur_time <= q && q <= cur_time + C[index] * T[index]) {
            writeln(index + 1);
        } else {
            cur_time += C[index] * T[index];
            index++;
            goto first;
        }
    }
}


In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again. Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative. As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.

The first line contains three integers n, m, k (1≤m≤n≤1000,0≤k≤10^6) — total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow n lines, each containing two integers: r (1≤r≤m) — index of the row, where belongs the corresponding tooth, and c (0≤c≤10^6) — its residual viability.
It's guaranteed that each tooth row has positive amount of teeth.

In the first line output the maximum amount of crucians that Valerie can consume for dinner.

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                int m = cin.readInt;
                int k = cin.readInt;

                int[][] t_arr = new int[][](m);
                for (int i = 0; i < n; i++) {
                        int a = cin.readInt;
                        int b = cin.readInt;
                        t_arr[a - 1] ~= b;
                }
                int count = 0;

                for (int i = 0; i < m; i++) {
                        count += t_arr[i].minElement;
                }

                if (count >= k) writeln(k);
                else writeln(count);
        }
}


Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.

The first line contains two space-separated integers n and m (1≤m≤n≤100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai (-1000≤ai≤1000) — prices of the TV sets.

Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.

import std;

void main() {
    int n, m;
    readf("%d %d\n", n, m);

    auto a = readln.chomp.split.to!(int[]);

    a.sort;

    int res;
    foreach (i, x; a) {
        if (i >= m || x >= 0) break;
        res += x;
    }

    res = -res;

    res.writeln;
}


Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1,l2,...,lm (1≤li≤n). For each number li he wants to know how many distinct numbers are staying on the positions li, li+1, ..., n. Formally, he want to find the number of distinct numbers among ali,ali+1,...,an.?Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each li.

The first line contains two integers n and m (1≤n,m≤10^5). The second line contains n integers a1, a2, ..., an (1≤ai≤10^5) — the array elements.
Next m lines contain integers l1,l2,...,lm. The i-th line contains integer li (1≤li≤n).

Print m lines — on the i-th line print the answer to the number li.

import std;

void main() {
    int n, m;
    readf("%d %d\n", n, m);

    auto a = readln.chomp.split.to!(int[]);

    int[int] list;
    foreach (x; a) ++list[x];

    auto len = list.length.to!int;
    auto cnts = new int[](n+1);
    foreach (i, x; a) {
        cnts[i+1] = len;

        --list[x];
        if (list[x] == 0) --len;
    }

    foreach (_; 0 .. m) {
        int l;
        readf("%d\n", l);

        cnts[l].writeln;
    }
}


The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.

The first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.

If the word t is a word s, written reversely, print YES, otherwise print NO.

import std;

void main() {
    string s, t;
    readf("%s\n%s\n", s, t);

    auto r = s.dup;
    r.reverse;

    writeln(r == t ? "YES" : "NO");
}

[{'input': ['code\r\nedoc\r\n'], 'output': ['YES\r\n']}, {'input': ['abb\r\naba\r\n'], 'output': ['NO\r\n']}, {'input': ['code\r\ncode\r\n'], 'output': ['NO\r\n']}, {'input': ['abacaba\r\nabacaba\r\n'], 'output': ['YES\r\n']}, {'input': ['q\r\nq\r\n'], 'output': ['YES\r\n']}, {'input': ['asrgdfngfnmfgnhweratgjkk\r\nasrgdfngfnmfgnhweratgjkk\r\n'], 'output': ['NO\r\n']}, {'input': ['z\r\na\r\n'], 'output': ['NO\r\n']}, {'input': ['asd\r\ndsa\r\n'], 'output': ['YES\r\n']}, {'input': ['abcdef\r\nfecdba\r\n'], 'output': ['NO\r\n']}, {'input': ['ywjjbirapvskozubvxoemscfwl\r\ngnduubaogtfaiowjizlvjcu\r\n'], 'output': ['NO\r\n']}, {'input': ['mfrmqxtzvgaeuleubcmcxcfqyruwzenguhgrmkuhdgnhgtgkdszwqyd\r\nmfxufheiperjnhyczclkmzyhcxntdfskzkzdwzzujdinf\r\n'], 'output': ['NO\r\n']}, {'input': ['bnbnemvybqizywlnghlykniaxxxlkhftppbdeqpesrtgkcpoeqowjwhrylpsziiwcldodcoonpimudvrxejjo\r\ntiynnekmlalogyvrgptbinkoqdwzuiyjlrldxhzjmmp\r\n'], 'output': ['NO\r\n']}, {'input': ['pwlpubwyhzqvcitemnhvvwkmwcaawjvdiwtoxyhbhbxerlypelevasmelpfqwjk\r\nstruuzebbcenziscuoecywugxncdwzyfozhljjyizpqcgkyonyetarcpwkqhuugsqjuixsxptmbnlfupdcfigacdhhrzb\r\n'], 'output': ['NO\r\n']}, {'input': ['gdvqjoyxnkypfvdxssgrihnwxkeojmnpdeobpecytkbdwujqfjtxsqspxvxpqioyfagzjxupqqzpgnpnpxcuipweunqch\r\nkkqkiwwasbhezqcfeceyngcyuogrkhqecwsyerdniqiocjehrpkljiljophqhyaiefjpavoom\r\n'], 'output': ['NO\r\n']}, {'input': ['umeszdawsvgkjhlqwzents\r\nhxqhdungbylhnikwviuh\r\n'], 'output': ['NO\r\n']}, {'input': ['juotpscvyfmgntshcealgbsrwwksgrwnrrbyaqqsxdlzhkbugdyx\r\nibqvffmfktyipgiopznsqtrtxiijntdbgyy\r\n'], 'output': ['NO\r\n']}, {'input': ['zbwueheveouatecaglziqmudxemhrsozmaujrwlqmppzoumxhamwugedikvkblvmxwuofmpafdprbcftew\r\nulczwrqhctbtbxrhhodwbcxwimncnexosksujlisgclllxokrsbnozthajnnlilyffmsyko\r\n'], 'output': ['NO\r\n']}, {'input': ['nkgwuugukzcv\r\nqktnpxedwxpxkrxdvgmfgoxkdfpbzvwsduyiybynbkouonhvmzakeiruhfmvrktghadbfkmwxduoqv\r\n'], 'output': ['NO\r\n']}, {'input': ['incenvizhqpcenhjhehvjvgbsnfixbatrrjstxjzhlmdmxijztphxbrldlqwdfimweepkggzcxsrwelodpnryntepioqpvk\r\ndhjbjjftlvnxibkklxquwmzhjfvnmwpapdrslioxisbyhhfymyiaqhlgecpxamqnocizwxniubrmpyubvpenoukhcobkdojlybxd\r\n'], 'output': ['NO\r\n']}, {'input': ['w\r\nw\r\n'], 'output': ['YES\r\n']}, {'input': ['vz\r\nzv\r\n'], 'output': ['YES\r\n']}, {'input': ['ry\r\nyr\r\n'], 'output': ['YES\r\n']}, {'input': ['xou\r\nuox\r\n'], 'output': ['YES\r\n']}, {'input': ['axg\r\ngax\r\n'], 'output': ['NO\r\n']}, {'input': ['zdsl\r\nlsdz\r\n'], 'output': ['YES\r\n']}, {'input': ['kudl\r\nldku\r\n'], 'output': ['NO\r\n']}, {'input': ['zzlzwnqlcl\r\nlclqnwzlzz\r\n'], 'output': ['YES\r\n']}, {'input': ['vzzgicnzqooejpjzads\r\nsdazjpjeooqzncigzzv\r\n'], 'output': ['YES\r\n']}, {'input': ['raqhmvmzuwaykjpyxsykr\r\nxkysrypjkyawuzmvmhqar\r\n'], 'output': ['NO\r\n']}, {'input': ['ngedczubzdcqbxksnxuavdjaqtmdwncjnoaicvmodcqvhfezew\r\nwezefhvqcdomvciaonjcnwdmtqajdvauxnskxbqcdzbuzcdegn\r\n'], 'output': ['YES\r\n']}, {'input': ['muooqttvrrljcxbroizkymuidvfmhhsjtumksdkcbwwpfqdyvxtrlymofendqvznzlmim\r\nmimlznzvqdnefomylrtxvydqfpwwbckdskmutjshhmfvdiumykziorbxcjlrrvttqooum\r\n'], 'output': ['YES\r\n']}, {'input': ['vxpqullmcbegsdskddortcvxyqlbvxmmkhevovnezubvpvnrcajpxraeaxizgaowtfkzywvhnbgzsxbhkaipcmoumtikkiyyaivg\r\ngviayyikkitmuomcpiakhbxszgbnhvwyzkftwoagzixaearxpjacrnvpvbuzenvovehkmmxvblqyxvctroddksdsgebcmlluqpxv\r\n'], 'output': ['YES\r\n']}, {'input': ['mnhaxtaopjzrkqlbroiyipitndczpunwygstmzevgyjdzyanxkdqnvgkikfabwouwkkbzuiuvgvxgpizsvqsbwepktpdrgdkmfdc\r\ncdfmkdgrdptkpewbsqvszipgxvgvuiuzbkkwuowbafkikgvnqdkxnayzdjygvezmtsgywnupocdntipiyiorblqkrzjpzatxahnm\r\n'], 'output': ['NO\r\n']}, {'input': ['dgxmzbqofstzcdgthbaewbwocowvhqpinehpjatnnbrijcolvsatbblsrxabzrpszoiecpwhfjmwuhqrapvtcgvikuxtzbftydkw\r\nwkdytfbztxukivgctvparqhuwmjfhwpceiozsprzbaxrslbbqasvlocjirbnntajphenipthvwocowbweabhtgdcztsfoqbzmxgd\r\n'], 'output': ['NO\r\n']}, {'input': ['gxoixiecetohtgjgbqzvlaobkhstejxdklghowtvwunnnvauriohuspsdmpzckprwajyxldoyckgjivjpmbfqtszmtocovxwgeh\r\nhegwxvocotmzstqfbmpjvijgkcyodlxyjawrpkczpmdspsuhoiruavnnnuwvtwohglkdxjetshkboalvzqbgjgthoteceixioxg\r\n'], 'output': ['YES\r\n']}, {'input': ['sihxuwvmaambplxvjfoskinghzicyfqebjtkysotattkahssumfcgrkheotdxwjckpvapbkaepqrxseyfrwtyaycmrzsrsngkh\r\nhkgnsrszrmcyaytwrfyesxrqpeakbpavpkcjwxdtoehkrgcfmusshakttatosyktjbeqfycizhgniksofjvxlpbmaamvwuxhis\r\n'], 'output': ['YES\r\n']}, {'input': ['ycnahksbughnonldzrhkysujmylcgcfuludjvjiahtkyzqvkopzqcnwhltbzfugzojqkjjlggmvnultascmygelkiktmfieok\r\nkoeifmtkiklegkmcsatlunvmggkjjlqjozgufzbtlhwncqzpokvqzykthaijvjdulufcgclymjusyyhrzdlnonhgubskhancy\r\n'], 'output': ['NO\r\n']}, {'input': ['wbqasaehtkfojruzyhrlgwmtyiovmzyfifslvlemhqheyaelzwnthrenjsbmntwaoryzwfbxmscmypvxlfmzpnkkjlvwvmtz\r\nztmvwvljkknpzmflxvpymcsmxbfwzyroawtnmbsjnerhtnwzleayehqhmelvlsfifyzmvoiytmwglrhyzurjofktheasaqbw\r\n'], 'output': ['YES\r\n']}, {'input': ['imippqurprbhfugngtgifelytadegwrgaefnfhbjjnmzikvjaccotqzemufqieqldgnbmviisgkynzeldlhqxuqphjfmyij\r\njiymfjhpquxqhldleznykgsiivmbngdlqeiqfumezqtoccajvkizmnjjbhfnfeagrwgedatylefigtgngufhbrpruqppimi\r\n'], 'output': ['YES\r\n']}, {'input': ['bikydffiuisckpvzqlteqfhegsagimodb\r\nbdomigasgehfqetlqzvpkcsiuiffdykib\r\n'], 'output': ['YES\r\n']}]


Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, i^th song will take ti minutes exactly. The Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.People have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.You as one of the organizers should make an optimal sсhedule for the event. For some reasons you must follow the conditions:  The duration of the event must be no more than d minutes;  Devu must complete all his songs;  With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible. If it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event.

The first line contains two space separated integers n, d (1≤n≤100; 1≤d≤10000). The second line contains n space-separated integers: t1,t2,...,tn (1≤ti≤100).

If there is no way to conduct all the songs of Devu, output -1. Otherwise output the maximum number of jokes that Churu can crack in the grand event.

Consider the first example. The duration of the event is 30 minutes. There could be maximum 5 jokes in the following way:
  First Churu cracks a joke in 5 minutes.  Then Devu performs the first song for 2 minutes.  Then Churu cracks 2 jokes in 10 minutes.  Now Devu performs second song for 2 minutes.  Then Churu cracks 2 jokes in 10 minutes.  Now finally Devu will perform his last song in 1 minutes.  Total time spent is 5+2+10+2+10+1=30 minutes.
Consider the second example. There is no way of organizing Devu's all songs. Hence the answer is -1.

import std.stdio;
import std.string;
import std.algorithm;
import std.conv;
import std.array;
import std.range;

void main()
{
    auto nm = readln.split.map!(to!int);
    auto ts = readln.split.map!(to!int);
    auto count = 0;
    auto d = nm[1]-ts[0];
    foreach(t; ts.dropOne) {
        if (d<0) {
            writeln(-1);
            return;
        } else {
            d-=10;
            count+=2;
        }
        //writef("d=%d c=%d ",d,count);
        d-=t;
    }
    if (d<0) {
        writeln(-1);
        return;
    }
    while (d>=10) {
        d-=10;
        count+=2;
    }
    if (d>=5) { count++;}
    writeln(count);
}


A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n=5, then after the third throw the child number 2 has the ball again. Overall, n-1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2≤n≤100) which indicates the number of kids in the circle.

In the single line print n-1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.

module cf_46A;

import std.stdio;

void main() {
    int n;

    readf("%d", &n);

    int step = 1, current = 0;
    for (int i = 1; i < n; ++i) {
        current = (current + step) % n;
        writef("%d ", current + 1);
        ++step;
    }
    writeln();
}


Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!

The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.

Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.

welcome to the
Codeforces
Beta
Round 5

and
good luck

import std.stdio;
import std.array;
import std.string;
import std.algorithm;

void main() {
    string[] text;
    int longest = 0;
    immutable border = "*";
    immutable fill = " ";

    string line;
    while ((line = readln) != null) {
        line = line.chomp;
        text ~= line;
        longest = max(longest, line.length);
    }

    bool roundLeft = true;

    writeln(border, border.replicate(longest), border);
    foreach (string s; text) {
        int numSpaces = (longest - s.length) / 2;

        string spaces = fill.replicate(numSpaces);

        if ((s.length + longest) % 2 == 1) {
            if (roundLeft) {
                writeln(border, spaces, s, spaces, fill, border);
            } else {
                writeln(border, fill, spaces, s, spaces, border);
            }

            roundLeft = !roundLeft;
        } else {
            writeln(border, spaces, s, spaces, border);
        }
    }
    writeln(border, border.replicate(longest), border);
}


The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.

The first line contains an integer n, which is the number of people in the crew (1≤n≤100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.

Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.

6
Jack captain
Alice woman
Charlie man
Teddy rat
Bob child
Julia woman

module cf_63A;

import std.stdio;
import std.algorithm;

struct Member {
    string name, type;

    int opCmp(ref const Member other) {
        int[string] TYPE_PRIORITY = [
            "rat": 1, "woman": 2, "child": 2, "man": 3, "captain": 4
        ];

        return TYPE_PRIORITY[type] - TYPE_PRIORITY[other.type];
    }
}

void main() {
    int n;
    Member[] crew;

    readf("%d", &n);
    crew = new Member[n];
    for (int i = 0; i < n; ++i) {
        readf(" %s %s\n", &crew[i].name, &crew[i].type);
    }

    sort!("a < b", SwapStrategy.stable)(crew);
    for (int i = 0; i < crew.length; ++i) {
        writeln(crew[i].name);
    }
}

[{'input': ['6\r\nJack captain\r\nAlice woman\r\nCharlie man\r\nTeddy rat\r\nBob child\r\nJulia woman\r\n'], 'output': ['Teddy\r\nAlice\r\nBob\r\nJulia\r\nCharlie\r\nJack\r\n']}, {'input': ['1\r\nA captain\r\n'], 'output': ['A\r\n']}, {'input': ['1\r\nAbcdefjhij captain\r\n'], 'output': ['Abcdefjhij\r\n']}, {'input': ['5\r\nA captain\r\nB man\r\nD woman\r\nC child\r\nE rat\r\n'], 'output': ['E\r\nD\r\nC\r\nB\r\nA\r\n']}, {'input': ['10\r\nCap captain\r\nD child\r\nC woman\r\nA woman\r\nE child\r\nMan man\r\nB child\r\nF woman\r\nRat rat\r\nRatt rat\r\n'], 'output': ['Rat\r\nRatt\r\nD\r\nC\r\nA\r\nE\r\nB\r\nF\r\nMan\r\nCap\r\n']}, {'input': ['5\r\nJoyxnkypf captain\r\nDxssgr woman\r\nKeojmnpd rat\r\nGdv man\r\nHnw man\r\n'], 'output': ['Keojmnpd\r\nDxssgr\r\nGdv\r\nHnw\r\nJoyxnkypf\r\n']}, {'input': ['11\r\nJue rat\r\nWyglbyphk rat\r\nGjlgu child\r\nGi man\r\nAttx rat\r\nTheorpkgx man\r\nYm rat\r\nX child\r\nB captain\r\nEnualf rat\r\nKktsgyuyv woman\r\n'], 'output': ['Jue\r\nWyglbyphk\r\nAttx\r\nYm\r\nEnualf\r\nGjlgu\r\nX\r\nKktsgyuyv\r\nGi\r\nTheorpkgx\r\nB\r\n']}, {'input': ['22\r\nWswwcvvm woman\r\nBtmfats rat\r\nI rat\r\nOcmtsnwx man\r\nUrcqv rat\r\nYghnogt woman\r\nWtyfc man\r\nWqle child\r\nUjfrelpu rat\r\nDstixj man\r\nAhksnio woman\r\nKhkvaap woman\r\nSjppvwm rat\r\nEgdmsv rat\r\nDank rat\r\nNquicjnw rat\r\nLh captain\r\nTdyaqaqln rat\r\nQtj rat\r\nTfgwijvq rat\r\nNbiso child\r\nNqthvbf woman\r\n'], 'output': ['Btmfats\r\nI\r\nUrcqv\r\nUjfrelpu\r\nSjppvwm\r\nEgdmsv\r\nDank\r\nNquicjnw\r\nTdyaqaqln\r\nQtj\r\nTfgwijvq\r\nWswwcvvm\r\nYghnogt\r\nWqle\r\nAhksnio\r\nKhkvaap\r\nNbiso\r\nNqthvbf\r\nOcmtsnwx\r\nWtyfc\r\nDstixj\r\nLh\r\n']}, {'input': ['36\r\nKqxmtwmsf child\r\nIze woman\r\nDlpr child\r\nK woman\r\nF captain\r\nRjwfeuhba rat\r\nBbv rat\r\nS rat\r\nMnmg woman\r\nSmzyx woman\r\nSr man\r\nQmhroracn rat\r\nSoqpuqock rat\r\nPibdq man\r\nIlrkrptx rat\r\nZaecfyqka man\r\nMmersfs child\r\nVvvocqi man\r\nHjeqxvq rat\r\nMpmb woman\r\nWmgu woman\r\nCerelmhoxi child\r\nA man\r\nDylv man\r\nXrdgmmtcpq woman\r\nXj woman\r\nCeh child\r\nOfccguo man\r\nNevr man\r\nAknkwdkq child\r\nBmo man\r\nLqo woman\r\nVej child\r\nT child\r\nRlijc man\r\nNsdtpdg woman\r\n'], 'output': ['Rjwfeuhba\r\nBbv\r\nS\r\nQmhroracn\r\nSoqpuqock\r\nIlrkrptx\r\nHjeqxvq\r\nKqxmtwmsf\r\nIze\r\nDlpr\r\nK\r\nMnmg\r\nSmzyx\r\nMmersfs\r\nMpmb\r\nWmgu\r\nCerelmhoxi\r\nXrdgmmtcpq\r\nXj\r\nCeh\r\nAknkwdkq\r\nLqo\r\nVej\r\nT\r\nNsdtpdg\r\nSr\r\nPibdq\r\nZaecfyqka\r\nVvvocqi\r\nA\r\nDylv\r\nOfccguo\r\nNevr\r\nBmo\r\nRlijc\r\nF\r\n']}, {'input': ['2\r\nA captain\r\nB man\r\n'], 'output': ['B\r\nA\r\n']}, {'input': ['2\r\nB woman\r\nA captain\r\n'], 'output': ['B\r\nA\r\n']}, {'input': ['2\r\nX child\r\nY captain\r\n'], 'output': ['X\r\nY\r\n']}, {'input': ['2\r\nX captain\r\nY rat\r\n'], 'output': ['Y\r\nX\r\n']}, {'input': ['6\r\nAbdelrhman captain\r\nAlice woman\r\nCharlie man\r\nTeddy rat\r\nBob child\r\nJulia woman\r\n'], 'output': ['Teddy\r\nAlice\r\nBob\r\nJulia\r\nCharlie\r\nAbdelrhman\r\n']}, {'input': ['4\r\nAratos captain\r\nMind child\r\nAman woman\r\nCarrot man\r\n'], 'output': ['Mind\r\nAman\r\nCarrot\r\nAratos\r\n']}]


Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.

The first line of the input contains a single integer n (1≤n≤92) — the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0≤ai≤15) — Vitya's records.
It's guaranteed that the input data is consistent.

If Vitya can be sure that the size of visible part of the moon on day n+1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.

In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.

module main;

import std.stdio;
import std.array;

immutable PROBLEM_NAME = "test";

void main ()
{
    //stdin = File(PROBLEM_NAME ~ ".txt","rt");
    //stdout = File(PROBLEM_NAME ~ ".out","wt");

    int n;
    readf(" %s", &n);
    auto a = new int [](n);
    for ( int i = 0; i < n;i++)
        readf(" %s", &a[i]);
    if (a.length == 1)
    {
        if (a[0] == 15)
            writeln("DOWN");
        if (a[0] == 0)
            writeln("UP");
        if (a[0] != 0 && a[0] != 15)
            writeln(-1);
    }
    else
    {
        if( a[a.length - 1] == 15 )
            writeln("DOWN");
        else if( a[a.length - 1] == 0)
            writeln("UP");
        else
        {
            if( a[a.length - 1] - a[a.length - 2] > 0)
                writeln("UP");
            else
                writeln("DOWN");
        }

    }
}


A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1≤i≤n) is displayed, squares 1,2,... ,i-1 has the saturation k, squares i+1,i+2,... ,n has the saturation 0, and the saturation of the square i can have any value from 0 to k.So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled: An example of such a bar can be seen on the picture. For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.

We are given 3 space-separated integers n, k, t (1≤n,k≤100, 0≤t≤100).

Print n numbers. The i-th of them should be equal to ai.

import std.format;
import std.stdio;

void main() {
    int n, k, t;
    readf("%s %s %s\n", n, k, t);
    int progress = cast(int)(cast(real)(t * n * k) / 100.0);
    int full = progress / k;
    foreach (i; 0..full) "%d ".format(k).write;
    if (full < n) {
        "%d ".format(progress - full * k).write;
        foreach (i; 0..n - full - 1) "%d ".format(0).write;
    }
    writeln;
}


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively.
The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.format;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip;
		int res = 5;
		string ans = "?????";
		foreach (c; 0..10_000)
		{
			int h = c / 100;
			if (n == 12 && !(1 <= h && h <= 12))
			{
				continue;
			}
			if (n == 24 && !(0 <= h && h <= 23))
			{
				continue;
			}
			int m = c % 100;
			if (!(0 <= m && m <= 59))
			{
				continue;
			}
			auto t = format ("%02d:%02d", h, m);
			auto cur = t.length.iota.map !(x => s[x] != t[x]).sum;
			if (res > cur)
			{
				res = cur;
				ans = t;
			}
		}
		writeln (ans);
	}
}


Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.

The first line contains an integer n, which is the number of contestants in the room (1≤n≤50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers:
  0≤plusi,minusi≤50;  150≤ai≤500 or ai=0, if problem A is not solved;  300≤bi≤1000 or bi=0, if problem B is not solved;  450≤ci≤1500 or ci=0, if problem C is not solved;  600≤di≤2000 or di=0, if problem D is not solved;  750≤ei≤2500 or ei=0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).

Print on the single line the handle of the room leader.

The number of points that each participant from the example earns, are as follows:
  Petr — 3860  tourist — 4140  Egor — 4030  c00lH4x0R — -350  some_participant — 2220 Thus, the leader of the room is tourist.

module cf_74a;

import std.stdio;

void main() {
  int n;
  string nick, leaderNick;
  int plus, minus, a, b, c, d, e;
  int leaderScore = int.min;

  readf("%d", &n);
  for (int i = 0; i < n; ++i) {
    readf(" %s ", &nick);
    readf(" %d %d", &plus, &minus);
    readf(" %d %d %d %d %d", &a, &b, &c, &d, &e);

    int curScore = plus * 100 - minus * 50 + a + b + c + d + e;
    if (curScore > leaderScore) {
      leaderScore = curScore;
      leaderNick = nick;
    }
  }

  writeln(leaderNick);
}


Haiku is a genre of Japanese traditional poetry.A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".Three phases from a certain poem are given. Determine whether it is haiku or not.

The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.

Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).

on  codeforces
beta round is running
   a rustling of keys

how many gallons
of edo s rain did you drink
                                cuckoo

module cf_78A;

import std.stdio;

bool isVowel(char letter) {
    return letter == 'a' || letter == 'e' || letter == 'i' ||
           letter == 'o' || letter == 'u';
}

void main() {
    immutable MAX_ROWS = 3;
    immutable ROW_SYLLABLES = [ 5, 7, 5 ];

    string row;

    bool haiku = true;
    for (int i = 0; i < MAX_ROWS; ++i) {
        readf("%s\n", &row);

        int syllables = 0;
        for (int j = 0; j < row.length; ++j) {
            if (isVowel(row[j])) {
                ++syllables;
            }
        }
        if (syllables != ROW_SYLLABLES[i]) {
            haiku = false;
        }
    }

    writeln(haiku? "YES": "NO");
}

[{'input': ['on  codeforces \r\nbeta round is running\r\n   a rustling of keys \r\n'], 'output': ['YES']}, {'input': ['how many gallons\r\nof edo s rain did you drink\r\n                                cuckoo\r\n'], 'output': ['NO']}, {'input': ['   hatsu shigure\r\n     saru   mo komino wo\r\nhoshige    nari\r\n'], 'output': ['YES']}, {'input': ['o vetus stagnum\r\n   rana    de ripa salit\r\n  ac   sonant     aquae\r\n'], 'output': ['NO']}, {'input': [' furuike ya\r\nkawazu tobikomu\r\nmizu no oto \r\n'], 'output': ['YES']}, {'input': ['  noch da leich\r\na   stamperl zum aufwaerma\r\n  da pfarrer   kimmt  a \r\n'], 'output': ['NO']}, {'input': ['  sommerfuglene        \r\n    hvorfor     bruge    mange ord\r\n et kan gore   det\r\n'], 'output': ['YES']}, {'input': ['     ab   der mittagszeit\r\n  ist es   etwas schattiger\r\n   ein  wolkenhimmel\r\n'], 'output': ['NO']}, {'input': ['tornando a vederli\r\ni fiori di ciliegio la sera\r\nson divenuti frutti\r\n'], 'output': ['NO']}, {'input': ['kutaburete\r\nyado karu koro ya\r\nfuji no hana\r\n'], 'output': ['YES']}, {'input': [' beginnings     of   poetry\r\n       the  rice       planting                songs                  \r\n    of    the interior\r\n'], 'output': ['NO']}, {'input': ['    door zomerregens\r\n    zijn de kraanvogelpoten\r\n    korter geworden\r\n'], 'output': ['NO']}, {'input': [' derevo na   srub\r\na     ptitsi    bezzabotno\r\n   gnezdishko tam vyut\r\n'], 'output': ['YES']}, {'input': ['writing in the dark\r\nunaware    that my pen\r\nhas   run out of ink\r\n'], 'output': ['NO']}, {'input': ['kusaaiu\r\nuieueua\r\nuo efaa\r\n'], 'output': ['YES']}, {'input': ['v\r\nh\r\np\r\n'], 'output': ['NO']}, {'input': ['i\r\ni\r\nu\r\n'], 'output': ['NO']}, {'input': ['awmio eoj\r\nabdoolceegood\r\nwaadeuoy\r\n'], 'output': ['YES']}, {'input': ['xzpnhhnqsjpxdboqojixmofawhdjcfbscq\r\nfoparnxnbzbveycoltwdrfbwwsuobyoz hfbrszy\r\nimtqryscsahrxpic agfjh  wvpmczjjdrnwj mcggxcdo\r\n'], 'output': ['YES']}, {'input': ['wxjcvccp cppwsjpzbd dhizbcnnllckybrnfyamhgkvkjtxxfzzzuyczmhedhztugpbgpvgh\r\nmdewztdoycbpxtp bsiw hknggnggykdkrlihvsaykzfiiw\r\ndewdztnngpsnn lfwfbvnwwmxoojknygqb hfe ibsrxsxr\r\n'], 'output': ['YES']}, {'input': ['nbmtgyyfuxdvrhuhuhpcfywzrbclp znvxw synxmzymyxcntmhrjriqgdjh xkjckydbzjbvtjurnf\r\nhhnhxdknvamywhsrkprofnyzlcgtdyzzjdsfxyddvilnzjziz qmwfdvzckgcbrrxplxnxf mpxwxyrpesnewjrx ajxlfj\r\nvcczq hddzd cvefmhxwxxyqcwkr  fdsndckmesqeq zyjbwbnbyhybd cta nsxzidl jpcvtzkldwd\r\n'], 'output': ['YES']}, {'input': ['rvwdsgdsrutgjwscxz pkd qtpmfbqsmctuevxdj kjzknzghdvxzlaljcntg jxhvzn  yciktbsbyscfypx x xhkxnfpdp\r\nwdfhvqgxbcts mnrwbr iqttsvigwdgvlxwhsmnyxnttedonxcfrtmdjjmacvqtkbmsnwwvvrlxwvtggeowtgsqld qj\r\nvsxcdhbzktrxbywpdvstr meykarwtkbm pkkbhvwvelclfmpngzxdmblhcvf qmabmweldplmczgbqgzbqnhvcdpnpjtch \r\n'], 'output': ['YES']}, {'input': ['brydyfsmtzzkpdsqvvztmprhqzbzqvgsblnz naait tdtiprjsttwusdykndwcccxfmzmrmfmzjywkpgbfnjpypgcbcfpsyfj k\r\nucwdfkfyxxxht lxvnovqnnsqutjsyagrplb jhvtwdptrwcqrovncdvqljjlrpxcfbxqgsfylbgmcjpvpl ccbcybmigpmjrxpu\r\nfgwtpcjeywgnxgbttgx htntpbk tkkpwbgxwtbxvcpkqbzetjdkcwad tftnjdxxjdvbpfibvxuglvx llyhgjvggtw jtjyphs\r\n'], 'output': ['YES']}, {'input': ['nyc aqgqzjjlj mswgmjfcxlqdscheskchlzljlsbhyn iobxymwzykrsnljj\r\nnnebeaoiraga\r\nqpjximoqzswhyyszhzzrhfwhf iyxysdtcpmikkwpugwlxlhqfkn\r\n'], 'output': ['NO']}, {'input': ['lzrkztgfe mlcnq ay ydmdzxh cdgcghxnkdgmgfzgahdjjmqkpdbskreswpnblnrc fmkwziiqrbskp\r\np oukeaz gvvy kghtrjlczyl qeqhgfgfej\r\nwfolhkmktvsjnrpzfxcxzqmfidtlzmuhxac wsncjgmkckrywvxmnjdpjpfydhk qlmdwphcvyngansqhl\r\n'], 'output': ['NO']}, {'input': ['yxcboqmpwoevrdhvpxfzqmammak\r\njmhphkxppkqkszhqqtkvflarsxzla pbxlnnnafqbsnmznfj qmhoktgzix qpmrgzxqvmjxhskkksrtryehfnmrt  dtzcvnvwp\r\nscwymuecjxhw rdgsffqywwhjpjbfcvcrnisfqllnbplpadfklayjguyvtrzhwblftclfmsr\r\n'], 'output': ['NO']}, {'input': ['qfdwsr jsbrpfmn znplcx nhlselflytndzmgxqpgwhpi ghvbbxrkjdirfghcybhkkqdzmyacvrrcgsneyjlgzfvdmxyjmph\r\nylxlyrzs drbktzsniwcbahjkgohcghoaczsmtzhuwdryjwdijmxkmbmxv yyfrokdnsx\r\nyw xtwyzqlfxwxghugoyscqlx pljtz aldfskvxlsxqgbihzndhxkswkxqpwnfcxzfyvncstfpqf\r\n'], 'output': ['NO']}, {'input': ['g rguhqhcrzmuqthtmwzhfyhpmqzzosa\r\nmhjimzvchkhejh irvzejhtjgaujkqfxhpdqjnxr dvqallgssktqvsxi\r\npcwbliftjcvuzrsqiswohi\r\n'], 'output': ['NO']}, {'input': [' ngxtlq iehiise vgffqcpnmsoqzyseuqqtggokymol zn\r\nvjdjljazeujwoubkcvtsbepooxqzrueaauokhepiquuopfild\r\ngoabauauaeotoieufueeknudiilupouaiaexcoapapu\r\n'], 'output': ['NO']}, {'input': ['ycnvnnqk mhrmhctpkfbc qbyvtjznmndqjzgbcxmvrpkfcll zwspfptmbxgrdv dsgkk nfytsqjrnfbhh pzdldzymvkdxxwh\r\nvnhjfwgdnyjptsmblyxmpzylsbjlmtkkwjcbqwjctqvrlqqkdsrktxlnslspvnn mdgsmzblhbnvpczmqkcffwhwljqkzmk hxcm\r\nrghnjvzcpprrgmtgytpkzyc mrdnnhpkwypwqbtzjyfwvrdwyjltbzxtbstzs xdjzdmx yjsqtzlrnvyssvglsdjrmsrfrcdpqt\r\n'], 'output': ['NO']}, {'input': ['ioeeaioeiuoeaeieuuieooaouiuouiioaueeaiaiuoaoiioeeaauooiuuieeuaeeoauieeaiuoieiaieuoauaaoioooieueueuai\r\nuooaoeeaoiuuoeioaoouaououoeioiaeueoioaiouaeaoioiuuaueeuaiuoiueoiuaoeeieeouaeeaeeieioeoiiieuuueuuieuo\r\naeeouieeieoueaioeoioooiouaeeeiaaioueauaueiouuuaieuuioiaeiueauueaoieauauoeueuaiueuuaueeoueauaeaoieeoo\r\n'], 'output': ['NO']}, {'input': ['mkgycgmrqtmlwj vddlbsgdptyfrcj nmrddjchydvbsyhgzytfzvwbhqmmhkpsyrcnknpsqrr wcnf wfvgskrnsmnrcqgcnc q\r\npn cclcyjjdp rqkpgyrvyyd hhynrochfa pthyffqvskazfshvzcmvhmsrxvquzkdvivlbfypwbgltfbjmhzljvgzmxjlrjdjq\r\nauuouieuaaauoooeoiuoaueuueauiuuuiaeuwuoiaeoeaieauieouoaeiiieiioiuuuiuauioiiuoeauueieaueiaioeuaoaaau\r\n'], 'output': ['NO']}, {'input': ['ab\r\na\r\na\r\n'], 'output': ['NO']}, {'input': ['on  codeforcs\r\nbeta round is runnineg\r\na rustling of keys\r\n'], 'output': ['NO']}, {'input': ['coooooooooooooooood\r\nd\r\nd\r\n'], 'output': ['NO']}, {'input': ['on  codeforces \r\nbeta round is runninog\r\n   a rustling of keys\r\n'], 'output': ['NO']}, {'input': ['aaaaaaaaaaaaaaa\r\na\r\na\r\n'], 'output': ['NO']}, {'input': ['aaaaaccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\r\naaaaaaaccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\r\naaaaaccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\r\n'], 'output': ['YES']}, {'input': ['cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\r\ncccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\r\ncccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\r\n'], 'output': ['NO']}, {'input': ['aaaaaa\r\naaaaaa\r\naaaaa\r\n'], 'output': ['NO']}]


Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.For each two integer numbers a and b such that l≤a≤r and x≤b≤y there is a potion with experience a and cost b in the store (that is, there are (r-l+1)·(y-x+1) potions).Kirill wants to buy a potion which has efficiency k. Will he be able to do this?

First string contains five integer numbers l, r, x, y, k (1≤l≤r≤10^7, 1≤x≤y≤10^7, 1≤k≤10^7).

Print "YES" without quotes if a potion with efficiency exactly k can be bought in the store and "NO" without quotes otherwise.
You can output each of the letters in any register.

// Try Codeforces
// author: Leonardone @ NEETSDKASU
import std.stdio      : readln, writeln;
import std.array      : split;
import std.string     : chomp;
import std.conv       : to;

auto gets() { return readln.chomp; }
auto getVals(T)() { return gets.split.to!(T[]); }

void main() {
    auto xs = getVals!long;
    auto l = xs[0], r = xs[1], x = xs[2], y = xs[3], k = xs[4];
    for (auto i = x; i <= y; i++) {
        auto v = i * k;
        if (l <= v && v <= r) {
            writeln("YES");
            return;
        }
    }
    writeln("NO");
}