Problem:
There are n processes in a queue. Each process has name i and time i .  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  name 1 time 1  name 2 time 2 ...  name n time n  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. name i and time i 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 ≤ time i ≤ 50000  1 ≤ length of name i ≤ 10  1 ≤ Sum of time i ≤ 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 (Python):
class Queue:
    def __init__(self,l):
        self.values = []
        self.l = l
        for _ in range(l):
            self.values.append(None)
        self.head = 0
        self.tail = 0
    def inc(self,n):
        if n+1 >= self.l:
            return 0
        else:
            return n+1
    def enqueue(self,v):
        if self.inc(self.head) == self.tail:
            print 'overflow'
            exit()
        self.values[self.head] = v
        self.head = self.inc(self.head)
    def dequeue(self):
        if self.head == self.tail:
            print 'underflow'
            exit()
        v = self.values[self.tail]
        self.tail = self.inc(self.tail)
        return v
    def size(self):
        if self.head >= self.tail:
            return self.head-self.tail
        else:
            self.head + (self.l-self.tail)

n,q = map(int,raw_input().split(' '))
queue = Queue(200000)
for _ in range(n):
    n,t = raw_input().split(' ')
    t = int(t)
    queue.enqueue((n,t))

c = 0
while queue.size()>0:
    n,t = queue.dequeue()
    if t <= q:
        c += t
        print n,c
    else:
        queue.enqueue((n,t-q))
        c += q

Solution (Python):
class Node:
    def __init__(self,v):
        self.v = v
        self.next = None

class Queue:
    def __init__(self):
        self.head = None
        self.tail = None
        self.size = 0

    def enqueue(self,v):
        self.size += 1
        n = Node(v)
        if self.tail == None:
            self.tail = n
        else:
            self.tail.next = n
            self.tail = n
        if self.head == None:
            self.head = self.tail
    def dequeue(self):
        if self.size == 0:
            print 'underflow'
            exit()
        self.size -= 1
        v = self.head.v
        self.head = self.head.next
        if self.head == None:
            self.tail = None
        return v

































n,q = map(int,raw_input().split(' '))
queue = Queue()
for _ in range(n):
    n,t = raw_input().split(' ')
    t = int(t)
    queue.enqueue((n,t))

c = 0
while queue.size>0:
    n,t = queue.dequeue()
    if t <= q:
        c += t
        print n,c
    else:
        queue.enqueue((n,t-q))
        c += q

Solution (Python):
n, q = [int(i) for i in input().split()]
process = []
for i in range(n):
    name, time = input().split()
    process.append([name, int(time)])

count = 0
while True:
    if len(process) == 0: break
    if process[0][1] <= q:
        count += process[0][1]
        print(process[0][0], count)
        process[0][1] = process[0][1] - q
        process.pop(0)
    else:
        count += q
        process[0][1] = process[0][1] - q
        process.append(process.pop(0))

Solution (Python):



def main():
    n, q = map(int, input().split())
    process = []
    finished = []
    counter = 0
    for _ in range(n):
        name, time = input().split()
        process.append((name, int(time)))

    while len(process)  > 0:
        name, time = process.pop(0)
        temp_q = q

        while True:
            
            if time <= 0:
                finished.append((name, counter))
                break

            
            
            if temp_q <= 0:
                process.append((name, time))
                break
            
            time -= 1
            temp_q -= 1
            counter += 1
    
    for name, time in finished:
        print(name, time)

if __name__ == "__main__":
    main()

Solution (Python):
class Queue:
    def __init__(self):
        self.queue = []

    def enqueue(self, value):
        self.queue.append(value)

    def dequeue(self):
        return self.queue.pop(0)

class Task:
    def __init__(self, name, time):
        self.name = name
        self.time = int(time)
        self.endtime = 0

    def __repr__(self):
        return '{} {}'.format(self.name, self.endtime)


def rr(queue, q):
    time = 0
    while len(queue.queue) > 0:
        task = queue.dequeue()
        if task.time > q:
            task.time -= q
            time += q
            queue.enqueue(task)
        else:
            time += task.time
            task.time = 0
            task.endtime = time
            print(task)

if __name__ == '__main__':
    nq = [int(s) for s in input().split()]
    N = nq[0]
    q = nq[1]
    queue = Queue()
    task_arr = [Task(*input().split()) for i in range(N)]
    for t in task_arr:
        queue.enqueue(t)
    rr(queue, q)

Solution (Python):
from collections import deque

process = deque(maxlen=100000)
n, q = [int(x) for x in input().split(' ')]

for i in range(n):
    name, time = input().split(' ')
    process.append([name, int(time)])

total_time = 0

while process:
    p_q = process.popleft()
    if p_q[1] > q:
        total_time += q
        p_q[1] -= q
        process.append(p_q)
    else:
        total_time += p_q[1]
        print('{} {}'.format(p_q[0], total_time))

Solution (Python):


import sys
from collections import deque

n, q = map(int, input().split())
total_time = 0
tasks = deque(map(lambda x: x.split(), sys.stdin.readlines()))

for task in tasks:
    task[1] = int(task[1])

try:
    while True:
        t = tasks.popleft()
        if t[1] - q <= 0:
            total_time += t[1]
            print(t[0], total_time)
        else:
            t[1] = t[1] - q
            total_time += q
            tasks.append(t)
except Exception:
    pass

Solution (Python):


import sys
from collections import deque

n, q = map(int, input().split())
total_time = 0
tasks = deque(map(lambda x: x.split(), sys.stdin.readlines()))

try:
    while True:
        t = tasks.popleft()
        if int(t[1]) - q <= 0:
            total_time += int(t[1])
            print(t[0], total_time)
        else:
            t[1] = str(int(t[1]) - q)
            total_time += q
            tasks.append(t)
except Exception:
    pass

Solution (Python):


import sys
from collections import deque

n, q = map(int, input().split())
total_time = 0
tasks = deque(map(lambda x: x.split(), sys.stdin.readlines()))

for task in tasks:
    task[1] = int(task[1])

try:
    while True:
        t = tasks.popleft()
        if t[1] <= q:
            total_time += t[1]
            print(t[0], total_time)
        else:
            t[1] -= q
            total_time += q
            tasks.append(t)
except Exception:
    pass

Solution (Python):


import sys
from collections import deque

n, q = map(int, input().split())
total_time = 0
tasks = deque(map(lambda x: x.split(), sys.stdin.readlines()))

for task in tasks:
    task[1] = int(task[1])

while tasks:
    t = tasks.popleft()
    if t[1] <= q:
        total_time += t[1]
        print(t[0], total_time)
    else:
        t[1] -= q
        total_time += q
        tasks.append(t)

Solution (Python):
queue,decrease = (int(n) for n in input().split(' '))
targ = []
for q in range(queue):
    targ.append([n for n in input().split(' ')])
length = 0
time = 0
while True:

    if int(targ[length][1]) - decrease <= 0:
        time += int(targ[length][1])
        print(str(targ[length][0]) + " " + str(time))
        targ.pop(length)
        queue -= 1
        if queue == 0:
            break
        length = (length) % queue
        
    else:
        time += decrease
        targ[length][1] = int(targ[length][1]) - decrease
        length = (length + 1) % queue

Solution (Python):



def main():
    n, q = map(int, input().split())
    process = []
    finished = []
    counter = 0
    for _ in range(n):
        name, time = input().split()
        process.append((name, int(time)))

    while len(process)  > 0:
        name, time = process.pop(0)
        temp_q = q

        while True:
            
            if time <= 0:
                finished.append((name, counter))
                break

            
            
            if temp_q <= 0:
                process.append((name, time))
                break
            
            time -= 1
            temp_q -= 1
            counter += 1
    
    for name, time in finished:
        print(name, time)

if __name__ == "__main__":
    main()

Solution (Python):
n, q = [int(i) for i in input().split(" ")]

current = 0
queue = []
for _ in range(n):
    name, t = input().split(" ")
    t = int(t)
    if t <= q:
        current += t
        print("{} {}".format(name, current))
    else:
        current += q
        queue.append((name, int(t - q)))

while len(queue) > 0:
    nqueue = []
    for name, t in queue:
        if t <= q:
            t = int(t)
            current += t
            print("{} {}".format(name, current))
        else:
            current += q
            nqueue.append((name, int(t - q)))
    queue = nqueue

Solution (Python):
import sys
n, q = list(map(int, input().split()))

robin = list(map(lambda y: [y[0], int(y[1])], list(map(lambda x: x.split(), sys.stdin))))

t = []
time = 0
while 0 < len(robin):
    r = robin.pop(0)
    remain = r[1]
    if q < remain:
        r[1] = remain - q
        robin.append(r)
        time += q
    else:
        time += remain
        t.append([r[0], time])

for i in t:
    print(' '.join(map(str, i)))

Solution (Python):
n, q = map(int, input().split())
process = [input().split() for _ in range(n)]

time = 0
while process:
    p = process.pop(0)
    if int(p[1]) <= q:
        time += int(p[1])
        print(p[0], time)
    else:
        time += q
        process.append([p[0], int(p[1])-q])

Solution (Python):
from collections import deque

nameq = deque()
timeq = deque()
n, q = map(int, raw_input().split())
for _ in xrange(n):
  name, time = raw_input().split()
  nameq.append(name)
  timeq.append(int(time))

t = 0
while nameq:
  name = nameq.popleft()
  time = timeq.popleft()
  if time > q:
    time -= q
    nameq.append(name)
    timeq.append(time)
    t += q
  else:
    t += time
    print "%s %d" % (name, t)

Solution (Python):


from collections import deque

queue = deque()
input_list = [int(i) for i in input().split()]
for i in range(input_list[0]):
    proc = input().split()
    queue.append([proc[0],int(proc[1])])

count = 0
while len(queue) != 0:
    proc = queue.popleft()
    if input_list[1] < proc[1]:
        queue.append([proc[0],proc[1]-input_list[1]])
        count += input_list[1]
    else:
        count += proc[1]
        print(proc[0] + ' ' + str(count))

Solution (Python):
time = 0
n, q = map(int, input().split())
qname = list(range(n))
qtime = list(range(n))
ename = []
etime = []
for i in range(n):
    inp = input().split()
    qname[i], qtime[i] = inp[0], int(inp[1])
while len(qtime) > 0:
    if qtime[0] <= q:
        time += qtime.pop(0)
        ename.append(qname.pop(0))
        etime.append(time)
    else:
        time += q
        qname.append(qname.pop(0))
        qtime.append(qtime.pop(0)-q)
for (a, b) in zip(ename, etime):
    print(a, b)

Solution (Python):
n, q = map(int, raw_input().split(" "))
process = {}
schedule = []
sec = 0

for i in range(n):
    p, time = raw_input().split(" ")
    process[p] = int(time)
    schedule.append(p)

while len(schedule) != 0:
    p = schedule.pop(0)
    if process[p] - q > 0:
        process[p] -= q
        schedule.append(p)
        sec += q
    else:
        sec += process[p]
        print(p + " " + str(sec))

Solution (Python):

def Queue(n,q,B):
    ans=[]
    ftime=0
    while len(B)>0:
        name=B[0].split(" ")[0]
        time=int(B[0].split(" ")[1])
        if time>q:
            ftime+=q
            newB=name+" "+str(time-q)
            B.append(newB)
            B.pop(0)
        else :
            ans.append(name+" "+str(ftime+time))
            B.pop(0)
            ftime+=time
    for i in range(n): 
        print(ans[i])
        
  
if __name__=="__main__":
    a=input()
    n=int(a.split(" ")[0])
    q=int(a.split(" ")[1])
    B=[]
    for i in range(n):
        B.append(input())
    Queue(n,q,B)

Solution (Python):
from collections import deque
n, q = map(int, input().split())
queue = deque([input().split() for _ in range(n)])
t = 0
while len(queue):
    p = queue.popleft()
    if int(p[1]) <= q:
        t += int(p[1])
        print(p[0], t)
    else:
        p[1] = int(p[1]) - q
        t += q
        queue.append(p)

Solution (Python):
import sys
import collections

(n, quantum) = map(int, input().split())
processes = [input().split() for i in range(n)]
for p in processes:
    p[1] = int(p[1])
queue = collections.deque(processes)
elapsed = 0
while queue:
    head = queue.popleft()
    if head[1] > quantum:
        head[1] -= quantum
        queue.append(head)
        elapsed += quantum
    else:
        elapsed += head[1]
        print(head[0], elapsed)

Solution (Python):
n,q=map(int,raw_input().split())

lst = []
for idx in xrange(n):
    name, time = raw_input().split()
    lst.append([name, int(time)])

idx = 0
tot = 0
while True:
  lst[idx][1] = lst[idx][1] - q
  if lst[idx][1] <= 0:
    tot += q + lst[idx][1]
    lst[idx][1] = 0
    print "%s %d" % (lst[idx][0], tot)
    lst.pop(idx)
    if len(lst)==0:
        break
  else:
    tot += q
    idx+=1
  if (idx >= len(lst)):
    idx = 0

Solution (Python):


import sys
from collections import deque


class Solution:
    @staticmethod
    def message_queue():
        
        
        _input = sys.stdin.readlines()
        task_num = int(_input[0].split()[0])
        task_time = int(_input[0].split()[1])
        total_time = 0

        task_deque = deque([{'name': i.split()[0], 'time': int(i.split()[1])} for i in _input[1:]])

        while task_deque:
            item = task_deque.popleft()
            if item['time'] <= task_time:
                total_time += item['time']
                print(item['name'], total_time)
            else:
                item['time'] -= task_time
                total_time += task_time
                task_deque.append(item)


if __name__ == '__main__':
    solution = Solution()
    solution.message_queue()

Solution (Python):


import sys
from collections import deque


class Solution:
    @staticmethod
    def message_queue():
        
        
        _input = sys.stdin.readlines()
        task_num = int(_input[0].split()[0])
        task_time = int(_input[0].split()[1])
        total_time = 0

        task_deque = deque([{'name': i.split()[0], 'time': int(i.split()[1])} for i in _input[1:]])

        while task_deque:
            item = task_deque.popleft()
            if item['time'] <= task_time:
                total_time += item['time']
                print(item['name'], total_time)
            else:
                item['time'] -= task_time
                total_time += task_time
                task_deque.append(item)


if __name__ == '__main__':
    solution = Solution()
    solution.message_queue()

Solution (Python):


import sys
from collections import deque


class Solution:
    @staticmethod
    def message_queue():
        
        
        task_num, task_time = map(int, input().split())
        _input = sys.stdin.readlines()
        
        task_deque = deque(map(lambda x: dict(name=x.split()[0], time=int(x.split()[-1])), _input))
        total_time = 0

        while task_deque:
            item = task_deque.popleft()
            if item['time'] <= task_time:
                total_time += item['time']
                print(item['name'], total_time)
            else:
                item['time'] -= task_time
                total_time += task_time
                task_deque.append(item)


if __name__ == '__main__':
    solution = Solution()
    solution.message_queue()

Solution (Python):


import sys
from collections import deque


class Solution:
    @staticmethod
    def message_queue():
        
        
        task_num, task_time = map(int, input().split())
        _input = sys.stdin.readlines()
        
        task_deque = deque(map(lambda x: dict(name=x.split()[0], time=int(x.split()[-1])), _input))
        total_time = 0

        while task_deque:
            item = task_deque.popleft()
            if item['time'] <= task_time:
                total_time += item['time']
                print(item['name'], total_time)
            else:
                item['time'] -= task_time
                total_time += task_time
                task_deque.append(item)


if __name__ == '__main__':
    solution = Solution()
    solution.message_queue()

Solution (Python):


from collections import deque

def process_task(task,qua, elapsed_time, complete_task):
	exe_task = task.popleft()
	t = int(exe_task[1])
	q = int(qua)

	if t-q  > 0:
		exe_task[1] = (t - q)
		task.append(exe_task)
		elapsed_time += q
	else:	
		elapsed_time += t
		complete_task.append([exe_task[0], elapsed_time])

	return elapsed_time,complete_task

def main():
	n,q = map(int, raw_input().split())
	task = [raw_input().split() for _ in range(n)]
	que = deque(task)
	ela_time = 0
	comp_task = []

	while len(que) != 0:
		ela_time , comp_task= process_task(que, q, ela_time,comp_task)	

	for i in comp_task:
		print i[0], i[1]



if __name__ == '__main__':
	main()

Solution (Python):



def rrs(quantum, process):
    finished_process = []
    queue = Queue()
    current_time = 0
    i = 0
    while len(finished_process) < len(process):
        if i < len(process):
            p_info = process[i]
            i += 1
        else:
            p_info = queue.dequeue()
        time = int(p_info[1])
        name = p_info[0]
        
        if time <= quantum:
            current_time += time
            finished_process.append((name, current_time))
        else:
            current_time += quantum
            queue.enqueue((name, time - quantum))
            
    return finished_process


class Queue:
    def __init__(self):
        self.data = []

    def enqueue(self, d):
        self.data.append(d)

    def dequeue(self):
        r = self.data[0]
        self.data = self.data[1:]
        return r
    
def main():
    info = input().split()
    n_list = int(info[0])
    quantum = int(info[1])
    target_list = [tuple(input().split()) for i in range(n_list)]
    print("\n".join([p + " " + str(t) for p,t in rrs(quantum, target_list)]))
    
if __name__ == "__main__":
    main()

Solution (Python):



def rrs(quantum, process):
    finished_process = []
    queue = Queue()
    current_time = 0
    i = 0
    
    while not len(finished_process) == len(process):
        
        if i < len(process):
            p_info = process[i]
            i += 1
        else:
            p_info = queue.dequeue()
        time = int(p_info[1])
        name = p_info[0]
        
        if time <= quantum:
            current_time += time
            finished_process.append((name, current_time))
        else:
            current_time += quantum
            queue.enqueue((name, time - quantum))
            
    return finished_process


class Queue:
    def __init__(self):
        self.data = []

    def enqueue(self, d):
        self.data.append(d)

    def dequeue(self):
        r = self.data[0]
        self.data = self.data[1:]
        return r
    
def main():
    info = input().split()
    n_list = int(info[0])
    quantum = int(info[1])
    target_list = [tuple(input().split()) for i in range(n_list)]
    print("\n".join([p + " " + str(t) for p,t in rrs(quantum, target_list)]))
    
if __name__ == "__main__":
    main()

Solution (Python):
class MyQueue(object):
    """
    My Queue class

    Attributes:
        queue: queue
        head
        tail
    """

    def __init__(self):
        """Constructor
        """
        self.length = 100010
        self.queue = []
        counter = 0
        while counter < self.length:
            self.queue.append(Process())
            counter += 1
        self.head = 0
        self.tail = 0

    def enqueue(self, name, time):
        """enqueue method

        Args:
            name: enqueued process name
            time: enqueued process time

        Returns:
            None
        """
        if self.is_full():
            print("[ERROR] Queue Overflow")
        else:
            self.queue[self.tail % self.length].name = name
            self.queue[self.tail % self.length].time = time
            self.tail += 1

    def dequeue(self):
        """dequeue method

        Returns:
            None
        """
        if self.is_empty():
            print("[ERROR] Queue Underflow")
        else:
            self.queue[self.head % self.length].name = ""
            self.queue[self.head % self.length].time = 0
            self.head += 1

    def is_empty(self):
        """check queue is empty or not

        Returns:
            Bool
        """
        if self.head == self.tail:
            return True
        else:
            return False

    def is_full(self):
        """chech whether queue is full or not"""
        if self.tail - self.head >= len(self.queue):
            return True
        else:
            return False


class Process(object):
    """process class
    """

    def __init__(self, name="", time=0):
        """constructor
        Args:
            name: name
            time: time
        """
        self.name = name
        self.time = time

    def forward_time(self, time):
        """time forward method

        Args:
            time: forward time interval

        Returns:
            remain time

        """
        self.time -= time
        return self.time


def time_forward(my_queue, interval, current_time):
    """

    Args:
        my_queue: queue
        interval: time step interval
        current_time: current time
    """

    value = my_queue.queue[my_queue.head % my_queue.length].forward_time(interval)
    if value < 0:
        current_time += (interval + value)
        print my_queue.queue[my_queue.head % my_queue.length].name, current_time
        my_queue.dequeue()
        return current_time

    elif value == 0:
        current_time += interval
        print my_queue.queue[my_queue.head % my_queue.length].name, current_time
        my_queue.dequeue()
        return current_time

    elif value > 0:
        current_time += interval
        copied_process = my_queue.queue[my_queue.head % my_queue.length]
        name, time = copied_process.name, copied_process.time
        my_queue.dequeue()
        my_queue.enqueue(name, time)
        return current_time


my_queue = MyQueue()
n, q = [int(x) for x in raw_input().split()]
counter = 0
while counter < n:
    name, time = raw_input().split()
    my_queue.enqueue(name, int(time))
    counter += 1

current_time = 0
while not my_queue.is_empty():
    current_time = time_forward(my_queue, q, current_time)

Solution (Python):
class MyQueue(object):
    """
    My Queue class

    Attributes:
        queue: queue
        head
        tail
    """

    def __init__(self):
        """Constructor
        """
        self.length = 100010
        self.queue = []
        counter = 0
        while counter < self.length:
            self.queue.append(Process())
            counter += 1
        self.head = 0
        self.tail = 0

    def enqueue(self, name, time):
        """enqueue method

        Args:
            name: enqueued process name
            time: enqueued process time

        Returns:
            None
        """
        if self.is_full():
            print("[ERROR] Queue Overflow")
        else:
            self.queue[self.tail % self.length].name = name
            self.queue[self.tail % self.length].time = time
            self.tail += 1

    def dequeue(self):
        """dequeue method

        Returns:
            None
        """
        if self.is_empty():
            print("[ERROR] Queue Underflow")
        else:
            self.queue[self.head % self.length].name = ""
            self.queue[self.head % self.length].time = 0
            self.head += 1

    def is_empty(self):
        """check queue is empty or not

        Returns:
            Bool
        """
        if self.head == self.tail:
            return True
        else:
            return False

    def is_full(self):
        """chech whether queue is full or not"""
        if self.tail - self.head >= len(self.queue):
            return True
        else:
            return False


class Process(object):
    """process class
    """

    def __init__(self, name="", time=0):
        """constructor
        Args:
            name: name
            time: time
        """
        self.name = name
        self.time = time

    def forward_time(self, time):
        """time forward method

        Args:
            time: forward time interval

        Returns:
            remain time

        """
        self.time -= time
        return self.time


def time_forward(my_queue, interval, current_time):
    """

    Args:
        my_queue: queue
        interval: time step interval
        current_time: current time
    """

    value = my_queue.queue[my_queue.head % my_queue.length].forward_time(interval)
    if value <= 0:
        current_time += (interval + value)
        print my_queue.queue[my_queue.head % my_queue.length].name, current_time
        my_queue.dequeue()


    elif value == 0:
        current_time += interval
        print my_queue.queue[my_queue.head % my_queue.length].name, current_time
        my_queue.dequeue()

    elif value > 0:
        current_time += interval
        name, time = my_queue.queue[my_queue.head % my_queue.length].name, \
                     my_queue.queue[my_queue.head % my_queue.length].time
        my_queue.dequeue()
        my_queue.enqueue(name, time)

    return current_time


my_queue = MyQueue()
n, q = [int(x) for x in raw_input().split()]
counter = 0
while counter < n:
    name, time = raw_input().split()
    my_queue.enqueue(name, int(time))
    counter += 1

current_time = 0
while not my_queue.is_empty():
    current_time = time_forward(my_queue, q, current_time)

Solution (Python):
class MyQueue(object):
    """
    My Queue class

    Attributes:
        queue: queue
        head
        tail
    """

    def __init__(self):
        """Constructor
        """
        self.length = 100010
        self.queue = []
        counter = 0
        while counter < self.length:
            self.queue.append(Process())
            counter += 1
        self.head = 0
        self.tail = 0

    def enqueue(self, name, time):
        """enqueue method

        Args:
            name: enqueued process name
            time: enqueued process time

        Returns:
            None
        """
        if self.is_full():
            print("[ERROR] Queue Overflow")
        else:
            self.queue[self.tail % self.length].name = name
            self.queue[self.tail % self.length].time = time
            self.tail += 1

    def dequeue(self):
        """dequeue method

        Returns:
            None
        """
        if self.is_empty():
            print("[ERROR] Queue Underflow")
        else:
            self.queue[self.head % self.length].name = ""
            self.queue[self.head % self.length].time = 0
            self.head += 1

    def is_empty(self):
        """check queue is empty or not

        Returns:
            Bool
        """
        if self.head == self.tail:
            return True
        else:
            return False

    def is_full(self):
        """chech whether queue is full or not"""
        if self.tail - self.head >= len(self.queue):
            return True
        else:
            return False


class Process(object):
    """process class
    """

    def __init__(self, name="", time=0):
        """constructor
        Args:
            name: name
            time: time
        """
        self.name = name
        self.time = time

    def forward_time(self, time):
        """time forward method

        Args:
            time: forward time interval

        Returns:
            remain time

        """
        self.time -= time
        return self.time


def time_forward(my_queue, interval, current_time):
    """

    Args:
        my_queue: queue
        interval: time step interval
        current_time: current time
    """

    value = my_queue.queue[my_queue.head % my_queue.length].forward_time(interval)
    if value <= 0:
        current_time += (interval + value)
        print my_queue.queue[my_queue.head % my_queue.length].name, current_time
        my_queue.dequeue()


    
    
    
    

    elif value > 0:
        current_time += interval
        name, time = my_queue.queue[my_queue.head % my_queue.length].name, \
                     my_queue.queue[my_queue.head % my_queue.length].time
        my_queue.dequeue()
        my_queue.enqueue(name, time)

    return current_time


my_queue = MyQueue()
n, q = [int(x) for x in raw_input().split()]
counter = 0
while counter < n:
    name, time = raw_input().split()
    my_queue.enqueue(name, int(time))
    counter += 1

current_time = 0
while not my_queue.is_empty():
    current_time = time_forward(my_queue, q, current_time)