Problem:
There are n processes in a queue. Each process has namei and timei. The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C

Solution in Rust (judge verdict: Accepted)

use std::env;
use std::io;
use std::io::prelude::*;
use std::collections::*;

//===================================================
// MACROs need to be defined above the use place ... ?
macro_rules! dprintln {
    ($($x:expr),*) => {{
        if $crate::is_debug_mode() {
            let f = || {println!( $($x),*)};
            f()
        }
    }}
}

/// Backward For-Loop Helper
///  from -> to (exclude `to`)
///
/// # Examples
/// see tests::macro_backward()
///
#[macro_export]
macro_rules! backward_ho {
    ($from:expr, $to:expr) => {{
        (($to + 1)..($from + 1)).rev()
    }};
}
//===================================================

fn main() {
    // Initialize
    set_debug_mode(false);
    for arg in env::args() {
        if arg == "--debug" {
            set_debug_mode(true);
        }
    }
    dprintln!("[DebugMode] {}", "On");

    // Execute
    dprintln!("=================");
    dprintln!("= READ INPUT     ");
    let stdin = io::stdin();
    let input = Input::new(stdin.lock());
    dprintln!("[Input] \n{:?}", input);
    dprintln!("=================");
    dprintln!("= INTERPRET INPUT");
    let q = input.into_quiz();
    dprintln!("[Quiz] \n{:?}", q);
    dprintln!("=================");
    dprintln!("= SOLVE QUIZE    ");
    let a = q.solve();
    dprintln!("[Answer] \n{:?}", a);
    dprintln!("=================");
    dprintln!("= PRINT ANSWER   ");
    a.print();
    dprintln!("=================");
}

#[derive(Debug, Clone)]
struct TaskName(String);

#[derive(Debug, Clone)]
struct Task {
    name: TaskName,
    remain_time: i32, // 1 <= remain_time <= 50,000
}

#[derive(Debug)]
struct Quiz {
    n: u32,      // 1 <= n <= 100,000
    q: u32,      // 1 <= q <= 1,000
    v: Vec<Task>, // v.len() == n
}

#[derive(Debug)]
struct Answer {
    v: Vec<(TaskName, i32)>,
    // v.len() == q.n
}

impl Input {
    fn into_quiz(mut self) -> Quiz {
        let n: u32 = self.parse_next().unwrap();
        let q: u32 = self.parse_next().unwrap();
        let mut v = Vec::new();
        for _i in 0..n {
            let name = self.parse_next().unwrap();
            let time = self.parse_next().unwrap();
            v.push( Task{
                name: TaskName( name ),
                remain_time: time,
            });
        }
        Quiz { n, q, v }
    }
}

impl Quiz {
    fn solve(self) -> Answer {
        let mut deque = VecDeque::new();
        let mut vv = Vec::new();
        
        for e in &self.v {
            let cname = e.name.clone();
            let time = e.remain_time;
            deque.push_back( (cname, time) );
        }

        let mut current_time = 0;
        while !deque.is_empty() {
            dprintln!("t:{}", current_time);
            dprintln!(" queue:{:?}", deque);
            let (name, time) = deque.pop_front().unwrap();
            let q = self.q as i32;
            if time - q > 0 {
                dprintln!("  time:{} - q:{} > 0", time, q);
                current_time += q;
                deque.push_back( (name, time-q) );
            } else {
                dprintln!("  time:{} - q:{} <= 0", time, q);
                current_time += time;
                vv.push( (name, current_time) );
            }
        }

        Answer{
            v: vv,
        }
    }
}

impl Answer {
    fn print(self) {
        for e in self.v {
            let (TaskName(name), time) = e;
            println!("{} {}", name, time); 
        }
    }
}

// =====================================================
// =
// =====================================================

//==================================================
// Stdin Reader
#[derive(Debug)]
pub enum Token {
    Word(String),
    LineBreak,
}

impl Token {
    pub fn is_word(&self) -> bool {
        match *self {
            Token::Word(ref _x) => true,
            _ => false,
        }
    }
}

#[derive(Debug)]
pub struct Input {
    tokens: Vec<Token>,
}

impl Input {
    pub fn new<T: BufRead>(input: T) -> Self {
        let lines = input.lines();
        let words = lines.flat_map(|l| tokenaize(l.unwrap()));
        let mut words = words.collect::<Vec<_>>();

        words.reverse();

        Input { tokens: words }
    }

    pub fn read_next_word(&mut self) -> Option<Token> {
        loop {
            match self.tokens.pop() {
                Some(Token::LineBreak) => (),
                x => return x,
            }
        }
    }

    pub fn parse_next<T>(&mut self) -> Option<T>
    where
        T: std::str::FromStr,
    {
        if let Some(Token::Word(str)) = self.read_next_word() {
            match str.parse() {
                Ok(x) => Some(x),
                _ => None,
            }
        } else {
            None
        }
    }

    pub fn parse_next_vec<T>(&mut self, size: usize) -> Option<Vec<T>>
    where
        T: std::str::FromStr,
    {
        let mut v = Vec::new();

        for _i in 0..size {
            if let Some(t) = self.parse_next() {
                v.push(t);
            } else {
                return None;
            }
        }

        Some(v)
    }

    pub fn parse_next_vec2<T>(&mut self, size2: usize, size1: usize) -> Option<Vec<Vec<T>>>
    where
        T: std::str::FromStr,
    {
        let mut v = Vec::new();

        for _i in 0..size2 {
            if let Some(t) = self.parse_next_vec(size1) {
                v.push(t);
            } else {
                return None;
            }
        }

        Some(v)
    }

    pub fn parse_all_remaining_into_vec<T>(&mut self) -> Vec<T>
    where
        T: std::str::FromStr,
    {
        let mut v = Vec::new();

        loop {
            match self.parse_next() {
                Some(x) => v.push(x),
                None => return v,
            }
        }
    }
}

fn tokenaize(str: String) -> Vec<Token> {
    let mut v = Vec::new();

    for w in str.split_whitespace() {
        v.push(Token::Word(w.to_string()));
    }
    v.push(Token::LineBreak);
    v
}

//==================================================
// Utility Functions
pub fn concat_vec_to_string<T>(v: &Vec<T>) -> String
where
    T: std::fmt::Display,
{
    let mut string = String::new();

    if let Some((h, t)) = v.split_first() {
        string = h.to_string();

        for obj in t {
            string = format!("{} {}", string, obj);
        }
    }

    return string;
}

//==================================================
// Debug Switch
static mut S_DEBUG_MODE: bool = false;
fn is_debug_mode() -> bool {
    unsafe { S_DEBUG_MODE }
}

fn set_debug_mode(mode: bool) {
    unsafe {
        S_DEBUG_MODE = mode;
    }
}

//==================================================
// Usage
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn macro_backward() {
        let mut v = Vec::new();
        for i in backward_ho!(5, 1) {
            v.push(i);
        }
        assert_eq!(vec![5, 4, 3, 2], v);
    }
}