There is a grid of squares with H+1 horizontal rows and W vertical columns.

You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top.

For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead.

Constraints

* 1 \leq H,W \leq 2\times 10^5
* 1 \leq A_i \leq B_i \leq W

Input

Input is given from Standard Input in the following format:


H W
A_1 B_1
A_2 B_2
:
A_H B_H


Output

Print H lines. The i-th line should contain the answer for the case k=i.

Example

Input

4 4
2 4
1 1
2 3
2 4


Output

1
3
6
-1

Difficulty: UNKNOWN_DIFFICULTY

Solutions:
import math
import itertools
import queue
import bisect
from collections import deque, defaultdict
import heapq as hpq
from sys import stdin, setrecursionlimit
ipt = stdin.readline
setrecursionlimit(10 ** 7)
mod = 10 ** 9 + 7
dir = [(-1, 0), (0, -1), (1, 0), (0, 1)]
alp = 'abcdefghijklmnopqrstuvwxyz'

class SegTree:

	def __init__(self, init_val, segfunc, ide_ele):
		n = len(init_val)
		self.segfunc = segfunc
		self.ide_ele = ide_ele
		self.num = 1 << (n - 1).bit_length()
		self.tree = [ide_ele] * 2 * self.num
		for i in range(n):
			self.tree[self.num + i] = init_val[i]
		for i in range(self.num - 1, 0, -1):
			self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

	def update(self, k, x):
		k += self.num
		self.tree[k] = x
		while k > 1:
			self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
			k >>= 1

	def query(self, l, r):
		res = self.ide_ele
		l += self.num
		r += self.num
		while l < r:
			if l & 1:
				res = self.segfunc(res, self.tree[l])
				l += 1
			if r & 1:
				res = self.segfunc(res, self.tree[r - 1])
			l >>= 1
			r >>= 1
		return res

class Binary_Indexed_Tree:

	def __init__(self, n):
		self.N = n
		self.BIT = [0] * (n + 1)
		self.l2 = 2 ** (len(format(n, 'b')) - 1)

	def get_sum(self, idx):
		res_sum = 0
		while idx > 0:
			res_sum += self.BIT[idx]
			idx -= idx & -idx
		return res_sum

	def query(self, l, r):
		return self.get_sum(r) - self.get_sum(l - 1)

	def add(self, idx, x):
		while idx <= self.N:
			self.BIT[idx] += x
			idx += idx & -idx
		return

	def lower_bound(self, w):
		if w <= 0:
			return 0
		x = 0
		k = self.l2
		while k > 0:
			if x + k <= self.N and self.BIT[x + k] < w:
				w -= self.BIT[x + k]
				x += k
			k //= 2
		return x + 1

	def upper_bound(self, w):
		x = 0
		k = self.l2
		while k > 0:
			if x + k <= self.N and self.BIT[x + k] <= w:
				w -= self.BIT[x + k]
				x += k
			k //= 2
		return x + 1

class std_map:

	def __init__(self, n, init):
		self.size = n
		self.keys = set()
		self.bit = Binary_Indexed_Tree(n + 1)
		self.dic = [init] * (n + 1)

	def __contains__(self, key):
		return key in self.keys

	def __getitem__(self, key):
		return self.dic[key]

	def __setitem__(self, key, value):
		if not key in self.keys:
			self.bit.add(key, 1)
			self.keys.add(key)
		self.dic[key] = value

	def remove(self, key):
		self.keys.remove(key)
		self.bit.add(key, -1)

	def lower_bound(self, k):
		return self.bit.lower_bound(self.bit.get_sum(k))

	def upper_bound(self, k):
		return self.bit.upper_bound(self.bit.get_sum(k))

	def kth_key(self, k):
		return self.bit.lower_bound(k)

	def kth_value(self, k):
		return self.dic[self.kth_key(k)]

	def prev_k(self, k):
		idx = self.bit.get_sum(k)
		if idx == 0:
			return -1
		return self.bit.lower_bound(idx - 1)

	def prev_k(self, k):
		idx = self.bit.get_sum(k)
		if idx == self.size:
			return -1
		return self.bit.lower_bound(idx + 1)

def main():
	(h, w) = map(int, ipt().split())
	st = SegTree([10 ** 18] + [0] * w + [10 ** 18], min, 10 ** 18)
	s = std_map(w + 2, 0)
	for i in range(1, w + 2):
		s.bit.add(i, 1)
	s.keys = set(range(w + 2))
	for i in range(h):
		(a, b) = map(int, ipt().split())
		pl = s.bit.get_sum(a - 1) + 1
		pa = s.kth_key(pl)
		mv = 10 ** 18
		while pa <= b:
			st.update(pa, 10 ** 18)
			mv = min(mv, s[pa] - pa)
			s.remove(pa)
			pa = s.kth_key(pl)
		mv += b + 1
		if b != w:
			if not b + 1 in s or s[b + 1] > mv:
				st.update(b + 1, mv)
				s[b + 1] = mv
		mv = st.tree[1]
		if mv == 10 ** 18:
			print(-1)
		else:
			print(mv + i + 1)
	return None
main()


class BalancingTree:

	def __init__(self, n):
		self.N = n
		self.root = self.node(1 << n, 1 << n)

	def debug(self):

		def debug_info(nd_):
			return (nd_.value - 1, nd_.pivot, nd_.left.value - 1 if nd_.left else -1, nd_.right.value - 1 if nd_.right else -1, nd_.cnt)

		def debug_node(nd):
			re = []
			if nd.left:
				re += debug_node(nd.left)
			if nd.value:
				re.append(debug_info(nd))
			if nd.right:
				re += debug_node(nd.right)
			return re
		print('Debug - root =', self.root.value - 1, debug_node(self.root)[:50])

	def append(self, v):
		v += 1
		nd = self.root
		while True:
			if v == nd.value:
				return 0
			else:
				(mi, ma) = (min(v, nd.value), max(v, nd.value))
				if mi < nd.pivot:
					nd.value = ma
					if nd.left:
						nd = nd.left
						v = mi
					else:
						p = nd.pivot
						nd.left = self.node(mi, p - (p & -p) // 2)
						break
				else:
					nd.value = mi
					if nd.right:
						nd = nd.right
						v = ma
					else:
						p = nd.pivot
						nd.right = self.node(ma, p + (p & -p) // 2)
						break

	def leftmost(self, nd):
		if nd.left:
			return self.leftmost(nd.left)
		return nd

	def rightmost(self, nd):
		if nd.right:
			return self.rightmost(nd.right)
		return nd

	def find_l(self, v):
		v += 1
		nd = self.root
		prev = 0
		if nd.value < v:
			prev = nd.value
		while True:
			if v <= nd.value:
				if nd.left:
					nd = nd.left
				else:
					return prev - 1
			else:
				prev = nd.value
				if nd.right:
					nd = nd.right
				else:
					return prev - 1

	def find_r(self, v):
		v += 1
		nd = self.root
		prev = 0
		if nd.value > v:
			prev = nd.value
		while True:
			if v < nd.value:
				prev = nd.value
				if nd.left:
					nd = nd.left
				else:
					return prev - 1
			elif nd.right:
				nd = nd.right
			else:
				return prev - 1

	@property
	def max(self):
		return self.find_l((1 << self.N) - 1)

	@property
	def min(self):
		return self.find_r(-1)

	@property
	def sum(self):
		return self.root.sum - self.root.value + 1

	@property
	def size(self):
		return self.root.cnt - 1

	def delete(self, v, nd=None, prev=None):
		v += 1
		if not nd:
			nd = self.root
		if not prev:
			prev = nd
		while v != nd.value:
			prev = nd
			if v <= nd.value:
				if nd.left:
					nd = nd.left
				else:
					return
			elif nd.right:
				nd = nd.right
			else:
				return
		if not nd.left and (not nd.right):
			if not prev.left:
				prev.right = None
			elif not prev.right:
				prev.left = None
			elif nd.pivot == prev.left.pivot:
				prev.left = None
			else:
				prev.right = None
		elif nd.right:
			nd.value = self.leftmost(nd.right).value
			self.delete(nd.value - 1, nd.right, nd)
		else:
			nd.value = self.rightmost(nd.left).value
			self.delete(nd.value - 1, nd.left, nd)

	def __contains__(self, v: int) -> bool:
		return self.find_r(v - 1) == v

	class node:

		def __init__(self, v, p):
			self.value = v
			self.pivot = p
			self.left = None
			self.right = None
import sys, heapq
input = sys.stdin.readline
(H, W) = map(int, input().split())
ban = [tuple(map(int, input().split())) for i in range(H)]
exist = [True for i in range(W + 1)]
que = [(0, i) for i in range(1, W + 1)]
heapq.heapify(que)
BT = BalancingTree(40)
for i in range(1, W + 1):
	tmp = (i << 20) + i
	BT.append(tmp)
erase = set()
for i in range(H):
	(a, b) = ban[i]
	erasemax = (-1, -1)
	while True:
		val = BT.find_r(a << 20)
		pos = val >> 20
		fr = val % (1 << 20)
		if pos <= b:
			erasemax = max(erasemax, (fr, pos - fr))
			erase.add((pos - fr, fr))
			exist[fr] = False
			BT.delete(val)
		else:
			if pos > b + 1 and erasemax[0] != -1 and (b + 1 <= W):
				BT.append((b + 1 << 20) + erasemax[0])
				deg = (erasemax[1], erasemax[0])
				erase.add(deg)
				heapq.heappush(que, (b + 1 - erasemax[0], erasemax[0]))
				exist[erasemax[0]] = True
			break
	while que and (not exist[que[0][1]] or que[0] in erase):
		heapq.heappop(que)
	if que:
		res = i + 1 + que[0][0]
		print(res)
	else:
		print(-1)


from heapq import *

class MultisetBIT:

	def __init__(self, maxvalue):
		self.n = maxvalue + 1
		self.k = 1 << (self.n + 1).bit_length() - 1
		self.data = [0] * (self.n + 1)

	def add(self, value):
		value += 1
		while value <= self.n:
			self.data[value] += 1
			value += value & -value

	def pop(self, value):
		value += 1
		while value <= self.n:
			self.data[value] -= 1
			value += value & -value

	def count_le(self, value):
		value += 1
		ret = 0
		while value > 0:
			ret += self.data[value]
			value -= value & -value
		return ret

	def count(self, first, last):
		last += 1
		ret = 0
		while first < last:
			ret += self.data[last]
			last -= last & -last
		while last < first:
			ret -= self.data[first]
			first -= first & -first
		return ret

	def bisect(self, count):
		ret = 0
		k = self.k
		while k > 0:
			if ret + k <= self.n and self.data[ret + k] < count:
				count -= self.data[ret + k]
				ret += k
			k >>= 1
		return ret

	def lower_bound(self, value):
		return self.bisect(self.count_le(value - 1) + 1)

	def upper_bound(self, value):
		return self.bisect(self.count_le(value) + 1)
(H, W) = map(int, input().split())
destination = MultisetBIT(W)
for i in range(W):
	destination.add(i)
destination_to_cost = {i: 0 for i in range(W)}
min_heapq = [0] * W
to_delete = []
for k in range(H):
	(A, B) = map(int, input().split())
	A -= 1
	B -= 1
	start_point = destination.lower_bound(A)
	point = start_point
	change_dest_flg = False
	while point < W and point < B + 1:
		change_dest_flg = True
		cost = destination_to_cost.pop(point)
		heappush(to_delete, cost)
		if B + 1 != W:
			if B + 1 in destination_to_cost:
				if destination_to_cost[B + 1] > B + 1 - point + cost:
					heappush(to_delete, destination_to_cost[B + 1])
					destination_to_cost[B + 1] = B + 1 - point + cost
					heappush(min_heapq, B + 1 - point + cost)
			else:
				destination_to_cost[B + 1] = B + 1 - point + cost
				heappush(min_heapq, B + 1 - point + cost)
				destination.add(B + 1)
		destination.pop(point)
		point = destination.upper_bound(point)
	while to_delete and min_heapq[0] == to_delete[0]:
		heappop(min_heapq)
		heappop(to_delete)
	if min_heapq:
		print(k + min_heapq[0] + 1)
	else:
		for _ in range(H - k):
			print(-1)
		exit()


from heapq import *
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

class BitSum:

	def __init__(self, n):
		self.n = n + 1
		self.table = [0] * self.n

	def add(self, i, x):
		i += 1
		while i < self.n:
			self.table[i] += x
			i += i & -i

	def sum(self, i):
		i += 1
		res = 0
		while i > 0:
			res += self.table[i]
			i -= i & -i
		return res

	def rank(self, x):
		idx = 0
		for lv in range((self.n - 1).bit_length() - 1, -1, -1):
			mid = idx + (1 << lv)
			if mid >= self.n:
				continue
			if self.table[mid] < x:
				x -= self.table[mid]
				idx += 1 << lv
		return idx

def solve():
	bit = BitSum(w + 1)
	for j in range(w):
		bit.add(j + 1, 1)
	cost = [0] * (w + 1)
	hp = [0] * w
	heapify(hp)
	rem = []
	for i in range(h):
		(l, r) = MI()
		r += 1
		if r <= w:
			cnt = bit.sum(r)
			if cnt:
				j = bit.rank(cnt)
				if l <= j < r:
					bit.add(r, 1)
					cost[r] = cost[j] + r - j
					heappush(hp, cost[r])
		cnt = bit.sum(l - 1)
		while 1:
			j = bit.rank(cnt + 1)
			if j >= r:
				break
			heappush(rem, cost[j])
			bit.add(j, -1)
		while hp and rem and (hp[0] == rem[0]):
			heappop(hp)
			heappop(rem)
		if hp:
			print(hp[0] + i + 1)
		else:
			print(-1)
(h, w) = MI()
solve()


from heapq import *

class erasable_heapq:
	__slots__ = ['data', 'to_delete']

	def __init__(self, data, allow_data_destruction=False):
		if allow_data_destruction:
			self.data = data
		else:
			self.data = data.copy()
		heapify(self.data)
		self.to_delete = []

	def top(self):
		while self.to_delete and self.to_delete[0] == self.data[0]:
			heappop(self.to_delete)
			heappop(self.data)
		return self.data[0]

	def push(self, elem):
		heappush(self.data, elem)

	def pop(self):
		while self.to_delete and self.to_delete[0] == self.data[0]:
			heappop(self.to_delete)
			heappop(self.data)
		return heappop(self.data)

	def pushpop(self, elem):
		while self.to_delete and self.to_delete[0] == self.data[0]:
			heappop(self.to_delete)
			heappop(self.data)
		return heappushpop(self.data, elem)

	def replace(self, elem):
		while self.to_delete and self.to_delete[0] == self.data[0]:
			heappop(self.to_delete)
			heappop(self.data)
		return heapreplace(self.data, elem)

	def erase(self, elem):
		heappush(self.to_delete, elem)

	def __bool__(self):
		while self.to_delete and self.to_delete[0] == self.data[0]:
			heappop(self.to_delete)
			heappop(self.data)
		return bool(self.data)

	def __len__(self):
		return len(self.data) - len(self.to_delete)

class MultisetBIT:
	__slots__ = ['n', 'k', 'data']

	def __init__(self, maxvalue, counter=None):
		self.n = maxvalue + 1
		self.k = 1 << (self.n + 1).bit_length() - 1
		self.data = [0] * (self.n + 1)
		if counter is not None:
			self.update(counter)

	def update(self, counter):
		if isinstance(counter, list):
			self.data = [0] + counter + [0] * (self.n - len(counter))
		else:
			self.data = [0] * (self.n + 1)
			for (k, v) in counter.items():
				self.data[k + 1] = v
		for i in range(1, self.n + 1):
			if i + (i & -i) <= self.n:
				self.data[i + (i & -i)] += self.data[i]

	def add(self, value):
		value += 1
		while value <= self.n:
			self.data[value] += 1
			value += value & -value

	def pop(self, value):
		value += 1
		while value <= self.n:
			self.data[value] -= 1
			value += value & -value

	def count_le(self, value):
		value += 1
		ret = 0
		while value > 0:
			ret += self.data[value]
			value -= value & -value
		return ret

	def count(self, first, last):
		last += 1
		ret = 0
		while first < last:
			ret += self.data[last]
			last -= last & -last
		while last < first:
			ret -= self.data[first]
			first -= first & -first
		return ret

	def bisect(self, count):
		ret = 0
		k = self.k
		while k > 0:
			if ret + k <= self.n and self.data[ret + k] < count:
				count -= self.data[ret + k]
				ret += k
			k //= 2
		return ret

	def lower_bound(self, value):
		return self.bisect(self.count_le(value - 1) + 1)

	def upper_bound(self, value):
		return self.bisect(self.count_le(value) + 1)
(H, W) = map(int, input().split())
destination = MultisetBIT(W, [1] * W)
destination_to_cost = {i: 0 for i in range(W)}
min_heapq = erasable_heapq([0] * W, True)
for k in range(H):
	(A, B) = map(int, input().split())
	A -= 1
	B -= 1
	start_point = destination.lower_bound(A)
	point = start_point
	change_dest_flg = False
	while point < W and point < B + 1:
		change_dest_flg = True
		cost = destination_to_cost.pop(point)
		min_heapq.erase(cost)
		if B + 1 != W:
			if B + 1 in destination_to_cost:
				if destination_to_cost[B + 1] > B + 1 - point + cost:
					min_heapq.erase(destination_to_cost[B + 1])
					destination_to_cost[B + 1] = B + 1 - point + cost
					min_heapq.push(B + 1 - point + cost)
			else:
				destination_to_cost[B + 1] = B + 1 - point + cost
				min_heapq.push(B + 1 - point + cost)
				destination.add(B + 1)
		destination.pop(point)
		point = destination.upper_bound(point)
	if min_heapq:
		print(k + min_heapq.top() + 1)
	else:
		for _ in range(H - k):
			print(-1)
		exit()


from heapq import *

class MultisetBIT:
	__slots__ = ['n', 'k', 'data']

	def __init__(self, maxvalue, counter=None):
		self.n = maxvalue + 1
		self.k = 1 << (self.n + 1).bit_length() - 1
		self.data = [0] * (self.n + 1)
		if counter is not None:
			self.update(counter)

	def update(self, counter):
		if isinstance(counter, list):
			self.data = [0] + counter + [0] * (self.n - len(counter))
		else:
			self.data = [0] * (self.n + 1)
			for (k, v) in counter.items():
				self.data[k + 1] = v
		for i in range(1, self.n + 1):
			if i + (i & -i) <= self.n:
				self.data[i + (i & -i)] += self.data[i]

	def add(self, value):
		value += 1
		while value <= self.n:
			self.data[value] += 1
			value += value & -value

	def pop(self, value):
		value += 1
		while value <= self.n:
			self.data[value] -= 1
			value += value & -value

	def count_le(self, value):
		value += 1
		ret = 0
		while value > 0:
			ret += self.data[value]
			value -= value & -value
		return ret

	def count(self, first, last):
		last += 1
		ret = 0
		while first < last:
			ret += self.data[last]
			last -= last & -last
		while last < first:
			ret -= self.data[first]
			first -= first & -first
		return ret

	def bisect(self, count):
		ret = 0
		k = self.k
		while k > 0:
			if ret + k <= self.n and self.data[ret + k] < count:
				count -= self.data[ret + k]
				ret += k
			k //= 2
		return ret

	def lower_bound(self, value):
		return self.bisect(self.count_le(value - 1) + 1)

	def upper_bound(self, value):
		return self.bisect(self.count_le(value) + 1)
(H, W) = map(int, input().split())
destination = MultisetBIT(W, {i: 1 for i in range(W)})
destination_to_cost = {i: 0 for i in range(W)}
min_heapq = [0] * W
to_delete = []
for k in range(H):
	(A, B) = map(int, input().split())
	A -= 1
	B -= 1
	start_point = destination.lower_bound(A)
	point = start_point
	change_dest_flg = False
	while point < W and point < B + 1:
		change_dest_flg = True
		cost = destination_to_cost.pop(point)
		heappush(to_delete, cost)
		if B + 1 != W:
			if B + 1 in destination_to_cost:
				if destination_to_cost[B + 1] > B + 1 - point + cost:
					heappush(to_delete, destination_to_cost[B + 1])
					destination_to_cost[B + 1] = B + 1 - point + cost
					heappush(min_heapq, B + 1 - point + cost)
			else:
				destination_to_cost[B + 1] = B + 1 - point + cost
				heappush(min_heapq, B + 1 - point + cost)
				destination.add(B + 1)
		destination.pop(point)
		point = destination.upper_bound(point)
	while to_delete and min_heapq[0] == to_delete[0]:
		heappop(min_heapq)
		heappop(to_delete)
	if min_heapq:
		print(k + min_heapq[0] + 1)
	else:
		for _ in range(H - k):
			print(-1)
		exit()


from __future__ import print_function
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
from collections.abc import Sequence, MutableSequence, ItemsView, KeysView, ValuesView, MutableSet, Set
from functools import wraps, reduce
from _thread import get_ident

def recursive_repr(fillvalue='...'):

	def decorating_function(user_function):
		repr_running = set()

		@wraps(user_function)
		def wrapper(self):
			key = (id(self), get_ident())
			if key in repr_running:
				return fillvalue
			repr_running.add(key)
			try:
				result = user_function(self)
			finally:
				repr_running.discard(key)
			return result
		return wrapper
	return decorating_function

class SortedList(MutableSequence):
	DEFAULT_LOAD_FACTOR = 1000

	def __init__(self, iterable=None, key=None):
		assert key is None
		self._len = 0
		self._load = self.DEFAULT_LOAD_FACTOR
		self._lists = []
		self._maxes = []
		self._index = []
		self._offset = 0
		if iterable is not None:
			self._update(iterable)

	def __new__(cls, iterable=None, key=None):
		if key is None:
			return object.__new__(cls)
		elif cls is SortedList:
			return object.__new__(SortedKeyList)
		else:
			raise TypeError('inherit SortedKeyList for key argument')

	@property
	def key(self):
		return None

	def _reset(self, load):
		values = reduce(iadd, self._lists, [])
		self._clear()
		self._load = load
		self._update(values)

	def clear(self):
		self._len = 0
		del self._lists[:]
		del self._maxes[:]
		del self._index[:]
		self._offset = 0
	_clear = clear

	def add(self, value):
		_lists = self._lists
		_maxes = self._maxes
		if _maxes:
			pos = bisect_right(_maxes, value)
			if pos == len(_maxes):
				pos -= 1
				_lists[pos].append(value)
				_maxes[pos] = value
			else:
				insort(_lists[pos], value)
			self._expand(pos)
		else:
			_lists.append([value])
			_maxes.append(value)
		self._len += 1

	def _expand(self, pos):
		_load = self._load
		_lists = self._lists
		_index = self._index
		if len(_lists[pos]) > _load << 1:
			_maxes = self._maxes
			_lists_pos = _lists[pos]
			half = _lists_pos[_load:]
			del _lists_pos[_load:]
			_maxes[pos] = _lists_pos[-1]
			_lists.insert(pos + 1, half)
			_maxes.insert(pos + 1, half[-1])
			del _index[:]
		elif _index:
			child = self._offset + pos
			while child:
				_index[child] += 1
				child = child - 1 >> 1
			_index[0] += 1

	def update(self, iterable):
		_lists = self._lists
		_maxes = self._maxes
		values = sorted(iterable)
		if _maxes:
			if len(values) * 4 >= self._len:
				values.extend(chain.from_iterable(_lists))
				values.sort()
				self._clear()
			else:
				_add = self.add
				for val in values:
					_add(val)
				return
		_load = self._load
		_lists.extend((values[pos:pos + _load] for pos in range(0, len(values), _load)))
		_maxes.extend((sublist[-1] for sublist in _lists))
		self._len = len(values)
		del self._index[:]
	_update = update

	def __contains__(self, value):
		_maxes = self._maxes
		if not _maxes:
			return False
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			return False
		_lists = self._lists
		idx = bisect_left(_lists[pos], value)
		return _lists[pos][idx] == value

	def discard(self, value):
		_maxes = self._maxes
		if not _maxes:
			return
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			return
		_lists = self._lists
		idx = bisect_left(_lists[pos], value)
		if _lists[pos][idx] == value:
			self._delete(pos, idx)

	def remove(self, value):
		_maxes = self._maxes
		if not _maxes:
			raise ValueError('{0!r} not in list'.format(value))
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			raise ValueError('{0!r} not in list'.format(value))
		_lists = self._lists
		idx = bisect_left(_lists[pos], value)
		if _lists[pos][idx] == value:
			self._delete(pos, idx)
		else:
			raise ValueError('{0!r} not in list'.format(value))

	def _delete(self, pos, idx):
		_lists = self._lists
		_maxes = self._maxes
		_index = self._index
		_lists_pos = _lists[pos]
		del _lists_pos[idx]
		self._len -= 1
		len_lists_pos = len(_lists_pos)
		if len_lists_pos > self._load >> 1:
			_maxes[pos] = _lists_pos[-1]
			if _index:
				child = self._offset + pos
				while child > 0:
					_index[child] -= 1
					child = child - 1 >> 1
				_index[0] -= 1
		elif len(_lists) > 1:
			if not pos:
				pos += 1
			prev = pos - 1
			_lists[prev].extend(_lists[pos])
			_maxes[prev] = _lists[prev][-1]
			del _lists[pos]
			del _maxes[pos]
			del _index[:]
			self._expand(prev)
		elif len_lists_pos:
			_maxes[pos] = _lists_pos[-1]
		else:
			del _lists[pos]
			del _maxes[pos]
			del _index[:]

	def _loc(self, pos, idx):
		if not pos:
			return idx
		_index = self._index
		if not _index:
			self._build_index()
		total = 0
		pos += self._offset
		while pos:
			if not pos & 1:
				total += _index[pos - 1]
			pos = pos - 1 >> 1
		return total + idx

	def _pos(self, idx):
		if idx < 0:
			last_len = len(self._lists[-1])
			if -idx <= last_len:
				return (len(self._lists) - 1, last_len + idx)
			idx += self._len
			if idx < 0:
				raise IndexError('list index out of range')
		elif idx >= self._len:
			raise IndexError('list index out of range')
		if idx < len(self._lists[0]):
			return (0, idx)
		_index = self._index
		if not _index:
			self._build_index()
		pos = 0
		child = 1
		len_index = len(_index)
		while child < len_index:
			index_child = _index[child]
			if idx < index_child:
				pos = child
			else:
				idx -= index_child
				pos = child + 1
			child = (pos << 1) + 1
		return (pos - self._offset, idx)

	def _build_index(self):
		row0 = list(map(len, self._lists))
		if len(row0) == 1:
			self._index[:] = row0
			self._offset = 0
			return
		head = iter(row0)
		tail = iter(head)
		row1 = list(starmap(add, zip(head, tail)))
		if len(row0) & 1:
			row1.append(row0[-1])
		if len(row1) == 1:
			self._index[:] = row1 + row0
			self._offset = 1
			return
		size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
		row1.extend(repeat(0, size - len(row1)))
		tree = [row0, row1]
		while len(tree[-1]) > 1:
			head = iter(tree[-1])
			tail = iter(head)
			row = list(starmap(add, zip(head, tail)))
			tree.append(row)
		reduce(iadd, reversed(tree), self._index)
		self._offset = size * 2 - 1

	def __delitem__(self, index):
		if isinstance(index, slice):
			(start, stop, step) = index.indices(self._len)
			if step == 1 and start < stop:
				if start == 0 and stop == self._len:
					return self._clear()
				elif self._len <= 8 * (stop - start):
					values = self._getitem(slice(None, start))
					if stop < self._len:
						values += self._getitem(slice(stop, None))
					self._clear()
					return self._update(values)
			indices = range(start, stop, step)
			if step > 0:
				indices = reversed(indices)
			(_pos, _delete) = (self._pos, self._delete)
			for index in indices:
				(pos, idx) = _pos(index)
				_delete(pos, idx)
		else:
			(pos, idx) = self._pos(index)
			self._delete(pos, idx)

	def __getitem__(self, index):
		_lists = self._lists
		if isinstance(index, slice):
			(start, stop, step) = index.indices(self._len)
			if step == 1 and start < stop:
				if start == 0 and stop == self._len:
					return reduce(iadd, self._lists, [])
				(start_pos, start_idx) = self._pos(start)
				start_list = _lists[start_pos]
				stop_idx = start_idx + stop - start
				if len(start_list) >= stop_idx:
					return start_list[start_idx:stop_idx]
				if stop == self._len:
					stop_pos = len(_lists) - 1
					stop_idx = len(_lists[stop_pos])
				else:
					(stop_pos, stop_idx) = self._pos(stop)
				prefix = _lists[start_pos][start_idx:]
				middle = _lists[start_pos + 1:stop_pos]
				result = reduce(iadd, middle, prefix)
				result += _lists[stop_pos][:stop_idx]
				return result
			if step == -1 and start > stop:
				result = self._getitem(slice(stop + 1, start + 1))
				result.reverse()
				return result
			indices = range(start, stop, step)
			return list((self._getitem(index) for index in indices))
		else:
			if self._len:
				if index == 0:
					return _lists[0][0]
				elif index == -1:
					return _lists[-1][-1]
			else:
				raise IndexError('list index out of range')
			if 0 <= index < len(_lists[0]):
				return _lists[0][index]
			len_last = len(_lists[-1])
			if -len_last < index < 0:
				return _lists[-1][len_last + index]
			(pos, idx) = self._pos(index)
			return _lists[pos][idx]
	_getitem = __getitem__

	def __setitem__(self, index, value):
		message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
		raise NotImplementedError(message)

	def __iter__(self):
		return chain.from_iterable(self._lists)

	def __reversed__(self):
		return chain.from_iterable(map(reversed, reversed(self._lists)))

	def reverse(self):
		raise NotImplementedError('use ``reversed(sl)`` instead')

	def islice(self, start=None, stop=None, reverse=False):
		_len = self._len
		if not _len:
			return iter(())
		(start, stop, _) = slice(start, stop).indices(self._len)
		if start >= stop:
			return iter(())
		_pos = self._pos
		(min_pos, min_idx) = _pos(start)
		if stop == _len:
			max_pos = len(self._lists) - 1
			max_idx = len(self._lists[-1])
		else:
			(max_pos, max_idx) = _pos(stop)
		return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)

	def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
		_lists = self._lists
		if min_pos > max_pos:
			return iter(())
		if min_pos == max_pos:
			if reverse:
				indices = reversed(range(min_idx, max_idx))
				return map(_lists[min_pos].__getitem__, indices)
			indices = range(min_idx, max_idx)
			return map(_lists[min_pos].__getitem__, indices)
		next_pos = min_pos + 1
		if next_pos == max_pos:
			if reverse:
				min_indices = range(min_idx, len(_lists[min_pos]))
				max_indices = range(max_idx)
				return chain(map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)))
			min_indices = range(min_idx, len(_lists[min_pos]))
			max_indices = range(max_idx)
			return chain(map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices))
		if reverse:
			min_indices = range(min_idx, len(_lists[min_pos]))
			sublist_indices = range(next_pos, max_pos)
			sublists = map(_lists.__getitem__, reversed(sublist_indices))
			max_indices = range(max_idx)
			return chain(map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)))
		min_indices = range(min_idx, len(_lists[min_pos]))
		sublist_indices = range(next_pos, max_pos)
		sublists = map(_lists.__getitem__, sublist_indices)
		max_indices = range(max_idx)
		return chain(map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices))

	def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):
		_maxes = self._maxes
		if not _maxes:
			return iter(())
		_lists = self._lists
		if minimum is None:
			min_pos = 0
			min_idx = 0
		elif inclusive[0]:
			min_pos = bisect_left(_maxes, minimum)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_left(_lists[min_pos], minimum)
		else:
			min_pos = bisect_right(_maxes, minimum)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_right(_lists[min_pos], minimum)
		if maximum is None:
			max_pos = len(_maxes) - 1
			max_idx = len(_lists[max_pos])
		elif inclusive[1]:
			max_pos = bisect_right(_maxes, maximum)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_lists[max_pos])
			else:
				max_idx = bisect_right(_lists[max_pos], maximum)
		else:
			max_pos = bisect_left(_maxes, maximum)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_lists[max_pos])
			else:
				max_idx = bisect_left(_lists[max_pos], maximum)
		return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)

	def __len__(self):
		return self._len

	def bisect_left(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			return self._len
		idx = bisect_left(self._lists[pos], value)
		return self._loc(pos, idx)

	def bisect_right(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_right(_maxes, value)
		if pos == len(_maxes):
			return self._len
		idx = bisect_right(self._lists[pos], value)
		return self._loc(pos, idx)
	bisect = bisect_right
	_bisect_right = bisect_right

	def count(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos_left = bisect_left(_maxes, value)
		if pos_left == len(_maxes):
			return 0
		_lists = self._lists
		idx_left = bisect_left(_lists[pos_left], value)
		pos_right = bisect_right(_maxes, value)
		if pos_right == len(_maxes):
			return self._len - self._loc(pos_left, idx_left)
		idx_right = bisect_right(_lists[pos_right], value)
		if pos_left == pos_right:
			return idx_right - idx_left
		right = self._loc(pos_right, idx_right)
		left = self._loc(pos_left, idx_left)
		return right - left

	def copy(self):
		return self.__class__(self)
	__copy__ = copy

	def append(self, value):
		raise NotImplementedError('use ``sl.add(value)`` instead')

	def extend(self, values):
		raise NotImplementedError('use ``sl.update(values)`` instead')

	def insert(self, index, value):
		raise NotImplementedError('use ``sl.add(value)`` instead')

	def pop(self, index=-1):
		if not self._len:
			raise IndexError('pop index out of range')
		_lists = self._lists
		if index == 0:
			val = _lists[0][0]
			self._delete(0, 0)
			return val
		if index == -1:
			pos = len(_lists) - 1
			loc = len(_lists[pos]) - 1
			val = _lists[pos][loc]
			self._delete(pos, loc)
			return val
		if 0 <= index < len(_lists[0]):
			val = _lists[0][index]
			self._delete(0, index)
			return val
		len_last = len(_lists[-1])
		if -len_last < index < 0:
			pos = len(_lists) - 1
			loc = len_last + index
			val = _lists[pos][loc]
			self._delete(pos, loc)
			return val
		(pos, idx) = self._pos(index)
		val = _lists[pos][idx]
		self._delete(pos, idx)
		return val

	def index(self, value, start=None, stop=None):
		_len = self._len
		if not _len:
			raise ValueError('{0!r} is not in list'.format(value))
		if start is None:
			start = 0
		if start < 0:
			start += _len
		if start < 0:
			start = 0
		if stop is None:
			stop = _len
		if stop < 0:
			stop += _len
		if stop > _len:
			stop = _len
		if stop <= start:
			raise ValueError('{0!r} is not in list'.format(value))
		_maxes = self._maxes
		pos_left = bisect_left(_maxes, value)
		if pos_left == len(_maxes):
			raise ValueError('{0!r} is not in list'.format(value))
		_lists = self._lists
		idx_left = bisect_left(_lists[pos_left], value)
		if _lists[pos_left][idx_left] != value:
			raise ValueError('{0!r} is not in list'.format(value))
		stop -= 1
		left = self._loc(pos_left, idx_left)
		if start <= left:
			if left <= stop:
				return left
		else:
			right = self._bisect_right(value) - 1
			if start <= right:
				return start
		raise ValueError('{0!r} is not in list'.format(value))

	def __add__(self, other):
		values = reduce(iadd, self._lists, [])
		values.extend(other)
		return self.__class__(values)
	__radd__ = __add__

	def __iadd__(self, other):
		self._update(other)
		return self

	def __mul__(self, num):
		values = reduce(iadd, self._lists, []) * num
		return self.__class__(values)
	__rmul__ = __mul__

	def __imul__(self, num):
		values = reduce(iadd, self._lists, []) * num
		self._clear()
		self._update(values)
		return self

	def __make_cmp(seq_op, symbol, doc):

		def comparer(self, other):
			if not isinstance(other, Sequence):
				return NotImplemented
			self_len = self._len
			len_other = len(other)
			if self_len != len_other:
				if seq_op is eq:
					return False
				if seq_op is ne:
					return True
			for (alpha, beta) in zip(self, other):
				if alpha != beta:
					return seq_op(alpha, beta)
			return seq_op(self_len, len_other)
		seq_op_name = seq_op.__name__
		comparer.__name__ = '__{0}__'.format(seq_op_name)
		doc_str = 'Return true if and only if sorted list is {0} `other`.\n        ``sl.__{1}__(other)`` <==> ``sl {2} other``\n        Comparisons use lexicographical order as with sequences.\n        Runtime complexity: `O(n)`\n        :param other: `other` sequence\n        :return: true if sorted list is {0} `other`\n        '
		comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
		return comparer
	__eq__ = __make_cmp(eq, '==', 'equal to')
	__ne__ = __make_cmp(ne, '!=', 'not equal to')
	__lt__ = __make_cmp(lt, '<', 'less than')
	__gt__ = __make_cmp(gt, '>', 'greater than')
	__le__ = __make_cmp(le, '<=', 'less than or equal to')
	__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
	__make_cmp = staticmethod(__make_cmp)

	def __reduce__(self):
		values = reduce(iadd, self._lists, [])
		return (type(self), (values,))

	@recursive_repr()
	def __repr__(self):
		return '{0}({1!r})'.format(type(self).__name__, list(self))

	def _check(self):
		try:
			assert self._load >= 4
			assert len(self._maxes) == len(self._lists)
			assert self._len == sum((len(sublist) for sublist in self._lists))
			for sublist in self._lists:
				for pos in range(1, len(sublist)):
					assert sublist[pos - 1] <= sublist[pos]
			for pos in range(1, len(self._lists)):
				assert self._lists[pos - 1][-1] <= self._lists[pos][0]
			for pos in range(len(self._maxes)):
				assert self._maxes[pos] == self._lists[pos][-1]
			double = self._load << 1
			assert all((len(sublist) <= double for sublist in self._lists))
			half = self._load >> 1
			for pos in range(0, len(self._lists) - 1):
				assert len(self._lists[pos]) >= half
			if self._index:
				assert self._len == self._index[0]
				assert len(self._index) == self._offset + len(self._lists)
				for pos in range(len(self._lists)):
					leaf = self._index[self._offset + pos]
					assert leaf == len(self._lists[pos])
				for pos in range(self._offset):
					child = (pos << 1) + 1
					if child >= len(self._index):
						assert self._index[pos] == 0
					elif child + 1 == len(self._index):
						assert self._index[pos] == self._index[child]
					else:
						child_sum = self._index[child] + self._index[child + 1]
						assert child_sum == self._index[pos]
		except BaseException:
			traceback.print_exc(file=sys.stdout)
			print('len', self._len)
			print('load', self._load)
			print('offset', self._offset)
			print('len_index', len(self._index))
			print('index', self._index)
			print('len_maxes', len(self._maxes))
			print('maxes', self._maxes)
			print('len_lists', len(self._lists))
			print('lists', self._lists)
			raise

def identity(value):
	return value

class SortedKeyList(SortedList):

	def __init__(self, iterable=None, key=identity):
		self._key = key
		self._len = 0
		self._load = self.DEFAULT_LOAD_FACTOR
		self._lists = []
		self._keys = []
		self._maxes = []
		self._index = []
		self._offset = 0
		if iterable is not None:
			self._update(iterable)

	def __new__(cls, iterable=None, key=identity):
		return object.__new__(cls)

	@property
	def key(self):
		return self._key

	def clear(self):
		self._len = 0
		del self._lists[:]
		del self._keys[:]
		del self._maxes[:]
		del self._index[:]
	_clear = clear

	def add(self, value):
		_lists = self._lists
		_keys = self._keys
		_maxes = self._maxes
		key = self._key(value)
		if _maxes:
			pos = bisect_right(_maxes, key)
			if pos == len(_maxes):
				pos -= 1
				_lists[pos].append(value)
				_keys[pos].append(key)
				_maxes[pos] = key
			else:
				idx = bisect_right(_keys[pos], key)
				_lists[pos].insert(idx, value)
				_keys[pos].insert(idx, key)
			self._expand(pos)
		else:
			_lists.append([value])
			_keys.append([key])
			_maxes.append(key)
		self._len += 1

	def _expand(self, pos):
		_lists = self._lists
		_keys = self._keys
		_index = self._index
		if len(_keys[pos]) > self._load << 1:
			_maxes = self._maxes
			_load = self._load
			_lists_pos = _lists[pos]
			_keys_pos = _keys[pos]
			half = _lists_pos[_load:]
			half_keys = _keys_pos[_load:]
			del _lists_pos[_load:]
			del _keys_pos[_load:]
			_maxes[pos] = _keys_pos[-1]
			_lists.insert(pos + 1, half)
			_keys.insert(pos + 1, half_keys)
			_maxes.insert(pos + 1, half_keys[-1])
			del _index[:]
		elif _index:
			child = self._offset + pos
			while child:
				_index[child] += 1
				child = child - 1 >> 1
			_index[0] += 1

	def update(self, iterable):
		_lists = self._lists
		_keys = self._keys
		_maxes = self._maxes
		values = sorted(iterable, key=self._key)
		if _maxes:
			if len(values) * 4 >= self._len:
				values.extend(chain.from_iterable(_lists))
				values.sort(key=self._key)
				self._clear()
			else:
				_add = self.add
				for val in values:
					_add(val)
				return
		_load = self._load
		_lists.extend((values[pos:pos + _load] for pos in range(0, len(values), _load)))
		_keys.extend((list(map(self._key, _list)) for _list in _lists))
		_maxes.extend((sublist[-1] for sublist in _keys))
		self._len = len(values)
		del self._index[:]
	_update = update

	def __contains__(self, value):
		_maxes = self._maxes
		if not _maxes:
			return False
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			return False
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				return False
			if _lists[pos][idx] == value:
				return True
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					return False
				len_sublist = len(_keys[pos])
				idx = 0

	def discard(self, value):
		_maxes = self._maxes
		if not _maxes:
			return
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			return
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				return
			if _lists[pos][idx] == value:
				self._delete(pos, idx)
				return
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					return
				len_sublist = len(_keys[pos])
				idx = 0

	def remove(self, value):
		_maxes = self._maxes
		if not _maxes:
			raise ValueError('{0!r} not in list'.format(value))
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			raise ValueError('{0!r} not in list'.format(value))
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				raise ValueError('{0!r} not in list'.format(value))
			if _lists[pos][idx] == value:
				self._delete(pos, idx)
				return
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					raise ValueError('{0!r} not in list'.format(value))
				len_sublist = len(_keys[pos])
				idx = 0

	def _delete(self, pos, idx):
		_lists = self._lists
		_keys = self._keys
		_maxes = self._maxes
		_index = self._index
		keys_pos = _keys[pos]
		lists_pos = _lists[pos]
		del keys_pos[idx]
		del lists_pos[idx]
		self._len -= 1
		len_keys_pos = len(keys_pos)
		if len_keys_pos > self._load >> 1:
			_maxes[pos] = keys_pos[-1]
			if _index:
				child = self._offset + pos
				while child > 0:
					_index[child] -= 1
					child = child - 1 >> 1
				_index[0] -= 1
		elif len(_keys) > 1:
			if not pos:
				pos += 1
			prev = pos - 1
			_keys[prev].extend(_keys[pos])
			_lists[prev].extend(_lists[pos])
			_maxes[prev] = _keys[prev][-1]
			del _lists[pos]
			del _keys[pos]
			del _maxes[pos]
			del _index[:]
			self._expand(prev)
		elif len_keys_pos:
			_maxes[pos] = keys_pos[-1]
		else:
			del _lists[pos]
			del _keys[pos]
			del _maxes[pos]
			del _index[:]

	def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):
		min_key = self._key(minimum) if minimum is not None else None
		max_key = self._key(maximum) if maximum is not None else None
		return self._irange_key(min_key=min_key, max_key=max_key, inclusive=inclusive, reverse=reverse)

	def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False):
		_maxes = self._maxes
		if not _maxes:
			return iter(())
		_keys = self._keys
		if min_key is None:
			min_pos = 0
			min_idx = 0
		elif inclusive[0]:
			min_pos = bisect_left(_maxes, min_key)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_left(_keys[min_pos], min_key)
		else:
			min_pos = bisect_right(_maxes, min_key)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_right(_keys[min_pos], min_key)
		if max_key is None:
			max_pos = len(_maxes) - 1
			max_idx = len(_keys[max_pos])
		elif inclusive[1]:
			max_pos = bisect_right(_maxes, max_key)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_keys[max_pos])
			else:
				max_idx = bisect_right(_keys[max_pos], max_key)
		else:
			max_pos = bisect_left(_maxes, max_key)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_keys[max_pos])
			else:
				max_idx = bisect_left(_keys[max_pos], max_key)
		return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
	_irange_key = irange_key

	def bisect_left(self, value):
		return self._bisect_key_left(self._key(value))

	def bisect_right(self, value):
		return self._bisect_key_right(self._key(value))
	bisect = bisect_right

	def bisect_key_left(self, key):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			return self._len
		idx = bisect_left(self._keys[pos], key)
		return self._loc(pos, idx)
	_bisect_key_left = bisect_key_left

	def bisect_key_right(self, key):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_right(_maxes, key)
		if pos == len(_maxes):
			return self._len
		idx = bisect_right(self._keys[pos], key)
		return self._loc(pos, idx)
	bisect_key = bisect_key_right
	_bisect_key_right = bisect_key_right

	def count(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			return 0
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		total = 0
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				return total
			if _lists[pos][idx] == value:
				total += 1
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					return total
				len_sublist = len(_keys[pos])
				idx = 0

	def copy(self):
		return self.__class__(self, key=self._key)
	__copy__ = copy

	def index(self, value, start=None, stop=None):
		_len = self._len
		if not _len:
			raise ValueError('{0!r} is not in list'.format(value))
		if start is None:
			start = 0
		if start < 0:
			start += _len
		if start < 0:
			start = 0
		if stop is None:
			stop = _len
		if stop < 0:
			stop += _len
		if stop > _len:
			stop = _len
		if stop <= start:
			raise ValueError('{0!r} is not in list'.format(value))
		_maxes = self._maxes
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			raise ValueError('{0!r} is not in list'.format(value))
		stop -= 1
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				raise ValueError('{0!r} is not in list'.format(value))
			if _lists[pos][idx] == value:
				loc = self._loc(pos, idx)
				if start <= loc <= stop:
					return loc
				elif loc > stop:
					break
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					raise ValueError('{0!r} is not in list'.format(value))
				len_sublist = len(_keys[pos])
				idx = 0
		raise ValueError('{0!r} is not in list'.format(value))

	def __add__(self, other):
		values = reduce(iadd, self._lists, [])
		values.extend(other)
		return self.__class__(values, key=self._key)
	__radd__ = __add__

	def __mul__(self, num):
		values = reduce(iadd, self._lists, []) * num
		return self.__class__(values, key=self._key)

	def __reduce__(self):
		values = reduce(iadd, self._lists, [])
		return (type(self), (values, self.key))

	@recursive_repr()
	def __repr__(self):
		type_name = type(self).__name__
		return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key)

	def _check(self):
		try:
			assert self._load >= 4
			assert len(self._maxes) == len(self._lists) == len(self._keys)
			assert self._len == sum((len(sublist) for sublist in self._lists))
			for sublist in self._keys:
				for pos in range(1, len(sublist)):
					assert sublist[pos - 1] <= sublist[pos]
			for pos in range(1, len(self._keys)):
				assert self._keys[pos - 1][-1] <= self._keys[pos][0]
			for (val_sublist, key_sublist) in zip(self._lists, self._keys):
				assert len(val_sublist) == len(key_sublist)
				for (val, key) in zip(val_sublist, key_sublist):
					assert self._key(val) == key
			for pos in range(len(self._maxes)):
				assert self._maxes[pos] == self._keys[pos][-1]
			double = self._load << 1
			assert all((len(sublist) <= double for sublist in self._lists))
			half = self._load >> 1
			for pos in range(0, len(self._lists) - 1):
				assert len(self._lists[pos]) >= half
			if self._index:
				assert self._len == self._index[0]
				assert len(self._index) == self._offset + len(self._lists)
				for pos in range(len(self._lists)):
					leaf = self._index[self._offset + pos]
					assert leaf == len(self._lists[pos])
				for pos in range(self._offset):
					child = (pos << 1) + 1
					if child >= len(self._index):
						assert self._index[pos] == 0
					elif child + 1 == len(self._index):
						assert self._index[pos] == self._index[child]
					else:
						child_sum = self._index[child] + self._index[child + 1]
						assert child_sum == self._index[pos]
		except BaseException:
			traceback.print_exc(file=sys.stdout)
			print('len', self._len)
			print('load', self._load)
			print('offset', self._offset)
			print('len_index', len(self._index))
			print('index', self._index)
			print('len_maxes', len(self._maxes))
			print('maxes', self._maxes)
			print('len_keys', len(self._keys))
			print('keys', self._keys)
			print('len_lists', len(self._lists))
			print('lists', self._lists)
			raise

class SortedSet(MutableSet, Sequence):

	def __init__(self, iterable=None, key=None):
		self._key = key
		if not hasattr(self, '_set'):
			self._set = set()
		self._list = SortedList(self._set, key=key)
		_set = self._set
		self.isdisjoint = _set.isdisjoint
		self.issubset = _set.issubset
		self.issuperset = _set.issuperset
		_list = self._list
		self.bisect_left = _list.bisect_left
		self.bisect = _list.bisect
		self.bisect_right = _list.bisect_right
		self.index = _list.index
		self.irange = _list.irange
		self.islice = _list.islice
		self._reset = _list._reset
		if key is not None:
			self.bisect_key_left = _list.bisect_key_left
			self.bisect_key_right = _list.bisect_key_right
			self.bisect_key = _list.bisect_key
			self.irange_key = _list.irange_key
		if iterable is not None:
			self._update(iterable)

	@classmethod
	def _fromset(cls, values, key=None):
		sorted_set = object.__new__(cls)
		sorted_set._set = values
		sorted_set.__init__(key=key)
		return sorted_set

	@property
	def key(self):
		return self._key

	def __contains__(self, value):
		return value in self._set

	def __getitem__(self, index):
		return self._list[index]

	def __delitem__(self, index):
		_set = self._set
		_list = self._list
		if isinstance(index, slice):
			values = _list[index]
			_set.difference_update(values)
		else:
			value = _list[index]
			_set.remove(value)
		del _list[index]

	def __make_cmp(set_op, symbol, doc):

		def comparer(self, other):
			if isinstance(other, SortedSet):
				return set_op(self._set, other._set)
			elif isinstance(other, Set):
				return set_op(self._set, other)
			return NotImplemented
		set_op_name = set_op.__name__
		comparer.__name__ = '__{0}__'.format(set_op_name)
		doc_str = 'Return true if and only if sorted set is {0} `other`.\n        ``ss.__{1}__(other)`` <==> ``ss {2} other``\n        Comparisons use subset and superset semantics as with sets.\n        Runtime complexity: `O(n)`\n        :param other: `other` set\n        :return: true if sorted set is {0} `other`\n        '
		comparer.__doc__ = dedent(doc_str.format(doc, set_op_name, symbol))
		return comparer
	__eq__ = __make_cmp(eq, '==', 'equal to')
	__ne__ = __make_cmp(ne, '!=', 'not equal to')
	__lt__ = __make_cmp(lt, '<', 'a proper subset of')
	__gt__ = __make_cmp(gt, '>', 'a proper superset of')
	__le__ = __make_cmp(le, '<=', 'a subset of')
	__ge__ = __make_cmp(ge, '>=', 'a superset of')
	__make_cmp = staticmethod(__make_cmp)

	def __len__(self):
		return len(self._set)

	def __iter__(self):
		return iter(self._list)

	def __reversed__(self):
		return reversed(self._list)

	def add(self, value):
		_set = self._set
		if value not in _set:
			_set.add(value)
			self._list.add(value)
	_add = add

	def clear(self):
		self._set.clear()
		self._list.clear()

	def copy(self):
		return self._fromset(set(self._set), key=self._key)
	__copy__ = copy

	def count(self, value):
		return 1 if value in self._set else 0

	def discard(self, value):
		_set = self._set
		if value in _set:
			_set.remove(value)
			self._list.remove(value)
	_discard = discard

	def pop(self, index=-1):
		value = self._list.pop(index)
		self._set.remove(value)
		return value

	def remove(self, value):
		self._set.remove(value)
		self._list.remove(value)

	def difference(self, *iterables):
		diff = self._set.difference(*iterables)
		return self._fromset(diff, key=self._key)
	__sub__ = difference

	def difference_update(self, *iterables):
		_set = self._set
		_list = self._list
		values = set(chain(*iterables))
		if 4 * len(values) > len(_set):
			_set.difference_update(values)
			_list.clear()
			_list.update(_set)
		else:
			_discard = self._discard
			for value in values:
				_discard(value)
		return self
	__isub__ = difference_update

	def intersection(self, *iterables):
		intersect = self._set.intersection(*iterables)
		return self._fromset(intersect, key=self._key)
	__and__ = intersection
	__rand__ = __and__

	def intersection_update(self, *iterables):
		_set = self._set
		_list = self._list
		_set.intersection_update(*iterables)
		_list.clear()
		_list.update(_set)
		return self
	__iand__ = intersection_update

	def symmetric_difference(self, other):
		diff = self._set.symmetric_difference(other)
		return self._fromset(diff, key=self._key)
	__xor__ = symmetric_difference
	__rxor__ = __xor__

	def symmetric_difference_update(self, other):
		_set = self._set
		_list = self._list
		_set.symmetric_difference_update(other)
		_list.clear()
		_list.update(_set)
		return self
	__ixor__ = symmetric_difference_update

	def union(self, *iterables):
		return self.__class__(chain(iter(self), *iterables), key=self._key)
	__or__ = union
	__ror__ = __or__

	def update(self, *iterables):
		_set = self._set
		_list = self._list
		values = set(chain(*iterables))
		if 4 * len(values) > len(_set):
			_list = self._list
			_set.update(values)
			_list.clear()
			_list.update(_set)
		else:
			_add = self._add
			for value in values:
				_add(value)
		return self
	__ior__ = update
	_update = update

	def __reduce__(self):
		return (type(self), (self._set, self._key))

	@recursive_repr()
	def __repr__(self):
		_key = self._key
		key = '' if _key is None else ', key={0!r}'.format(_key)
		type_name = type(self).__name__
		return '{0}({1!r}{2})'.format(type_name, list(self), key)

	def _check(self):
		_set = self._set
		_list = self._list
		_list._check()
		assert len(_set) == len(_list)
		assert all((value in _set for value in _list))

class SortedDict(dict):

	def __init__(self, *args, **kwargs):
		if args and (args[0] is None or callable(args[0])):
			_key = self._key = args[0]
			args = args[1:]
		else:
			_key = self._key = None
		self._list = SortedList(key=_key)
		_list = self._list
		self._list_add = _list.add
		self._list_clear = _list.clear
		self._list_iter = _list.__iter__
		self._list_reversed = _list.__reversed__
		self._list_pop = _list.pop
		self._list_remove = _list.remove
		self._list_update = _list.update
		self.bisect_left = _list.bisect_left
		self.bisect = _list.bisect_right
		self.bisect_right = _list.bisect_right
		self.index = _list.index
		self.irange = _list.irange
		self.islice = _list.islice
		self._reset = _list._reset
		if _key is not None:
			self.bisect_key_left = _list.bisect_key_left
			self.bisect_key_right = _list.bisect_key_right
			self.bisect_key = _list.bisect_key
			self.irange_key = _list.irange_key
		self._update(*args, **kwargs)

	@property
	def key(self):
		return self._key

	@property
	def iloc(self):
		try:
			return self._iloc
		except AttributeError:
			warnings.warn('sorted_dict.iloc is deprecated. Use SortedDict.keys() instead.', DeprecationWarning, stacklevel=2)
			_iloc = self._iloc = SortedKeysView(self)
			return _iloc

	def clear(self):
		dict.clear(self)
		self._list_clear()

	def __delitem__(self, key):
		dict.__delitem__(self, key)
		self._list_remove(key)

	def __iter__(self):
		return self._list_iter()

	def __reversed__(self):
		return self._list_reversed()

	def __setitem__(self, key, value):
		if key not in self:
			self._list_add(key)
		dict.__setitem__(self, key, value)
	_setitem = __setitem__

	def copy(self):
		return self.__class__(self._key, self.items())
	__copy__ = copy

	@classmethod
	def fromkeys(cls, iterable, value=None):
		return cls(((key, value) for key in iterable))

	def keys(self):
		return SortedKeysView(self)

	def items(self):
		return SortedItemsView(self)

	def values(self):
		return SortedValuesView(self)

	class _NotGiven(object):

		def __repr__(self):
			return '<not-given>'
	__not_given = _NotGiven()

	def pop(self, key, default=__not_given):
		if key in self:
			self._list_remove(key)
			return dict.pop(self, key)
		else:
			if default is self.__not_given:
				raise KeyError(key)
			return default

	def popitem(self, index=-1):
		if not self:
			raise KeyError('popitem(): dictionary is empty')
		key = self._list_pop(index)
		value = dict.pop(self, key)
		return (key, value)

	def peekitem(self, index=-1):
		key = self._list[index]
		return (key, self[key])

	def setdefault(self, key, default=None):
		if key in self:
			return self[key]
		dict.__setitem__(self, key, default)
		self._list_add(key)
		return default

	def update(self, *args, **kwargs):
		if not self:
			dict.update(self, *args, **kwargs)
			self._list_update(dict.__iter__(self))
			return
		if not kwargs and len(args) == 1 and isinstance(args[0], dict):
			pairs = args[0]
		else:
			pairs = dict(*args, **kwargs)
		if 10 * len(pairs) > len(self):
			dict.update(self, pairs)
			self._list_clear()
			self._list_update(dict.__iter__(self))
		else:
			for key in pairs:
				self._setitem(key, pairs[key])
	_update = update

	def __reduce__(self):
		items = dict.copy(self)
		return (type(self), (self._key, items))

	@recursive_repr()
	def __repr__(self):
		_key = self._key
		type_name = type(self).__name__
		key_arg = '' if _key is None else '{0!r}, '.format(_key)
		item_format = '{0!r}: {1!r}'.format
		items = ', '.join((item_format(key, self[key]) for key in self._list))
		return '{0}({1}{{{2}}})'.format(type_name, key_arg, items)

	def _check(self):
		_list = self._list
		_list._check()
		assert len(self) == len(_list)
		assert all((key in self for key in _list))

def _view_delitem(self, index):
	_mapping = self._mapping
	_list = _mapping._list
	dict_delitem = dict.__delitem__
	if isinstance(index, slice):
		keys = _list[index]
		del _list[index]
		for key in keys:
			dict_delitem(_mapping, key)
	else:
		key = _list.pop(index)
		dict_delitem(_mapping, key)

class SortedKeysView(KeysView, Sequence):
	__slots__ = ()

	@classmethod
	def _from_iterable(cls, it):
		return SortedSet(it)

	def __getitem__(self, index):
		return self._mapping._list[index]
	__delitem__ = _view_delitem

class SortedItemsView(ItemsView, Sequence):
	__slots__ = ()

	@classmethod
	def _from_iterable(cls, it):
		return SortedSet(it)

	def __getitem__(self, index):
		_mapping = self._mapping
		_mapping_list = _mapping._list
		if isinstance(index, slice):
			keys = _mapping_list[index]
			return [(key, _mapping[key]) for key in keys]
		key = _mapping_list[index]
		return (key, _mapping[key])
	__delitem__ = _view_delitem

class SortedValuesView(ValuesView, Sequence):
	__slots__ = ()

	def __getitem__(self, index):
		_mapping = self._mapping
		_mapping_list = _mapping._list
		if isinstance(index, slice):
			keys = _mapping_list[index]
			return [_mapping[key] for key in keys]
		key = _mapping_list[index]
		return _mapping[key]
	__delitem__ = _view_delitem
INF = 1000000
(H, W) = map(int, input().split())
SL = SortedList()
SS = SortedSet()
SS.irange
for i in range(1, W + 1):
	SS.add(i * 10 ** 6 + i)
	SL.add(0)
for i in range(H):
	(A, B) = map(int, input().split())
	cur = -1
	for X in list(SS.irange(A * 10 ** 6, (B + 1) * 10 ** 6 - 1)):
		y = X % 10 ** 6
		x = X // 10 ** 6
		cur = max(cur, y)
		SS.remove(X)
		SL.remove(x - y)
	if cur > -1 and B < W:
		SS.add((B + 1) * 10 ** 6 + cur)
		SL.add(B + 1 - cur)
	if SL:
		print(SL[0] + i + 1)
	else:
		print(-1)


class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))
(H, W) = [int(x) for x in input().split()]
AB = [[int(x) - 1 for x in input().split()] for i in range(H)]
inf = float('inf')
DEBUG = False
if DEBUG:
	grid = [['.' for i in range(W)] for j in range(H + 1)]
	for i in range(H):
		for j in range(AB[i][0], AB[i][1] + 1):
			grid[i][j] = '_'
	for row in grid:
		print(''.join(row))
	dp = [0 for i in range(W)]
	print('\t'.join(map(str, dp)))
	for i in range(H):
		nextDp = [inf for i in range(W)]
		(a, b) = AB[i]
		for j in range(W):
			if not a <= j <= b:
				nextDp[j] = dp[j] + 1
		for j in range(1, W):
			nextDp[j] = min(nextDp[j], nextDp[j - 1] + 1)
		dp = nextDp
		print('\t'.join(map(str, dp)), '\t\tbest', min(dp))
	print('\n\n')
indexToRight = {i: 0 for i in range(W)}
indices = SortedList()
rights = SortedList()
for (k, v) in indexToRight.items():
	indices.add(k)
	rights.add(v)
for i in range(H):
	(a, b) = AB[i]
	lo = indices.bisect_left(a)
	hi = indices.bisect_right(b + 1)
	if hi - lo:
		bestRight = inf
		for j in reversed(range(lo, hi)):
			index = indices[j]
			right = indexToRight[index]
			indices.remove(index)
			rights.remove(right)
			bestRight = min(bestRight, right + b + 1 - index)
		if b + 1 != W:
			indices.add(b + 1)
			rights.add(bestRight)
			indexToRight[b + 1] = bestRight
	if not indices:
		print(-1)
	else:
		downMoves = i + 1
		rightMoves = rights[0]
		print(downMoves + rightMoves)


import sys, heapq
input = sys.stdin.buffer.readline

def main():
	(h, w) = map(int, input().split())
	dp = [0] * (w + 1)
	res = [0] * w
	anti = []
	BIT = [0] * (w + 1)

	def BIT_query(idx):
		res_sum = 0
		while idx > 0:
			res_sum += BIT[idx]
			idx -= idx & -idx
		return res_sum

	def BIT_update(idx, x):
		while idx <= w:
			BIT[idx] += x
			idx += idx & -idx
	for i in range(1, w + 1):
		BIT_update(i, 1)
	for i in range(1, h + 1):
		(a, b) = map(int, input().split())
		x = a - 1
		if x != 0 and x != w + 1 and (dp[x] == -1):
			k = BIT_query(x - 1)
			if k != 0:
				ok = x
				ng = 0
				while ok - ng > 1:
					mid = (ok + ng) // 2
					if BIT_query(mid) == k:
						ok = mid
					else:
						ng = mid
				dp[x] = dp[ok] + (x - ok)
				BIT_update(x, 1)
				heapq.heappush(res, dp[x])
		x = b + 1
		if x != 0 and x != w + 1 and (dp[x] == -1):
			k = BIT_query(x - 1)
			if k != 0:
				ok = x
				ng = 0
				while ok - ng > 1:
					mid = (ok + ng) // 2
					if BIT_query(mid) == k:
						ok = mid
					else:
						ng = mid
				dp[x] = dp[ok] + (x - ok)
				BIT_update(x, 1)
				heapq.heappush(res, dp[x])
		k = BIT_query(a - 1) + 1
		while True:
			ng = a - 1
			ok = b + 1
			while ok - ng > 1:
				mid = (ok + ng) // 2
				if BIT_query(mid) >= k:
					ok = mid
				else:
					ng = mid
			if ok > b or dp[ok] == -1:
				break
			heapq.heappush(anti, dp[ok])
			dp[ok] = -1
			BIT_update(ok, -1)
		while anti and res and (anti[0] == res[0]):
			heapq.heappop(anti)
			heapq.heappop(res)
		if res:
			print(res[0] + i)
		else:
			print(-1)
main()