Problem:

Score : 300 points

Problem Statement

There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N).

For each k = 1,2,\dots,N, find the answer to the following question:

Rng is in City k.
Rng can perform the following move arbitrarily many times:

move to another city that has a smaller x-coordinate and a smaller y-coordinate, or a larger x-coordinate and a larger y-coordinate, than the city he is currently in.

How many cities (including City k) are reachable from City k?

Constraints

1 \leq N \leq 200,000

(x_1, x_2, \dots, x_N) is a permutation of (1, 2, \dots, N).

(y_1, y_2, \dots, y_N) is a permutation of (1, 2, \dots, N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print N lines. In i-th line print the answer to the question when k = i.

Sample Input 1

4
1 4
2 3
3 1
4 2

Sample Output 1

1
1
2
2

Rng can reach City 4 from City 3, or conversely City 3 from City 4.

Sample Input 2

7
6 4
4 3
3 5
7 1
2 7
5 2
1 6

Sample Output 2

3
3
1
1
2
3
2



Sample input:
4
1 4
2 3
3 1
4 2


Sample output:
1
1
2
2

Submission status: Accepted

Solution code:
class UnionFind():
    "Either 0-indexed or 1-indexed"

    __slots__ = ["parent"]

    def __init__(self, size):
        self.parent = [-1] * (size + 1)
    
    def find(self, a):
        path = []
        while self.parent[a] > 0:
            path.append(a)
            a = self.parent[a]
        for child in path:
            self.parent[child] = a
        return a

    def union(self, a, b):
        a = self.find(a)
        b = self.find(b)

        if a == b:
            return
        else:
            if self.parent[a] == self.parent[b]:
                self.parent[a] = b
                self.parent[b] -= 1
            elif self.parent[a] < self.parent[b]: #aのほうが大きい
                self.parent[b] = a
            else:
                self.parent[a] = b #bのほうが大きい
        
    def same(self, a, b):
        return self.find(a) == self.find(b)


# 基本的に番兵を入れて使うのがいいでしょう。

class MultisetBIT:
    """
    最大値が小さい数について、その重複を許した集合を管理する。
    最大値 maxvalue を受け取り、[0, maxvalue] を管理する。
    counter は辞書型かリスト型で、counter[i] が i の個数を持つことを仮定する。
    counter が与えられなかった場合は、全て個数 0 で初期化される。
    基本的に閉区間で管理する。
    内部では受け取った数を +1 したものをindexとして持っているので注意。
    """

    __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):
        """
        counter を受け取って、それを反映させる。
        counter は辞書型かリスト型で、counter[i] が i の個数を持つことを仮定する。
        計算量は、n を要素の最大値として、 O(n) となる。
        """
        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, count = 1):
        """
        与えられた引数を Multiset に加える。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        value += 1
        while value <= self.n:
            self.data[value] += count
            value += value & -value

    def pop(self, value, count = 1):
        """
        Multiset から与えられた引数を取り除く。
        与えられた引数が Multiset に入っているかのチェックは行わなず、
        単にその個数を 1 減らすだけなので注意。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        value += 1
        while value <= self.n:
            self.data[value] -= count
            value += value & -value

    def count_le(self, value):
        """
        Multiset 内の要素 elem のうち、0 <= elem <= value を満たすものを数える。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        value += 1
        ret = 0
        while value > 0:
            ret += self.data[value]
            value -= value & -value
        return ret

    def count(self, first, last):
        """
        Multiset 内の要素 elem のうち、first <= elem <= last を満たすものを数える。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        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 __getitem__(self, index):
        if isinstance(index, slice):
            return self.count(index.start, index.stop - 1)
        else:
            return self.count(index, index)

    def bisect(self, count):
        """
        Multiset 内の要素 elem のうち、count <= count_le(elem) を満たす最小のelemを返す。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        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):
        """
        Multiset 内の要素 elem のうち、value <= elem を満たす最小のelemを返す。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        return self.bisect(self.count_le(value - 1) + 1)

    def upper_bound(self, value):
        """
        Multiset 内の要素 elem のうち、value < elem を満たす最小のelemを返す。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        return self.bisect(self.count_le(value) + 1)


N = int(input())
xys = [tuple(map(int, input().split())) for i in range(N)]
x2i = {x: i for i, (x, y) in enumerate(xys)}

xys.sort(key=lambda t: t[0])

splitted = [True] * (N - 1)

mbit = MultisetBIT(N + 1)
for n, (x, y) in enumerate(xys[:-1]):
    mbit.add(y)
    if mbit.count_le(N - n - 1):
        splitted[n] = False

# print(splitted)

mbit = MultisetBIT(N + 1)
for n, (x, y) in enumerate(xys[:0:-1]):
    mbit.add(y)
    if mbit.count(n + 2, N + 1):
        splitted[N - 2 - n] = False

# print(splitted)

ans = [0] * N
s = set()
for (x, y), flg in zip(xys, splitted):
    i = x2i[x]
    s.add(i)
    if flg:
        for i in s:
            ans[i] = len(s)
        s = set()

s.add(x2i[xys[-1][0]])
for i in s:
    ans[i] = len(s)
print(*ans, sep='\n')

Submission status: Accepted

Solution code:
class Union:
  def __init__(s, num):
    s.T = [-1 for i in range(num)]
 
  def root(s, x):
    if s.T[x] < 0: return x, -s.T[x]
    t, k = s.root(s.T[x])
    s.T[x] = t
    return t, k
 
  def merge(s, x, y):
    an, am = s.root(x)
    bn, bm = s.root(y)
    if an == bn: return False
    if am < bm: an, bn  = bn, an
    s.T[an] += s.T[bn]
    s.T[bn] = an
    return True
 
  def size(s, x):
    return s.root(x)[1]

  def same(s, x, y):
    return s.root(x)[0] == s.root(y)[0]

import heapq
pop = heapq.heappop
push = heapq.heappush
q  = []

N = int(input())
xy = [list(map(int, input().split())) for _ in range(N)]

uni = Union(N)

xyn = [[0] * 3 for _ in range(N)]
for i in range(N):
  x, y = xy[i]
  xyn[i] = [x, y, i]

xyn.sort()
x, y, n = xyn[0]
push(q, (y << 20) + n)
for i in range(1, N):
  x, y, n = xyn[i]
  m = pop(q)
  yy, nn = m >> 20, m % (1 << 20)
  if yy < y:
    uni.merge(nn, n)
    while q:
      p = pop(q)
      yy, nn = p >> 20, p % (1 << 20)
      if yy < y:
        uni.merge(nn, n)
      else:
        push(q, (yy << 20) + nn)
        break
  else:
    push(q, (y << 20) + n)
  push(q, m)

for i in range(N):
  print(uni.root(i)[1])

Submission status: Accepted

Solution code:
# Union-Find
# https://note.nkmk.me/python-union-find/
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N = int(input())
xy = [0] * N
i_to_x = {}
for i in range(N):
    x, y = map(int, input().split())
    xy[i] = (x-1, y-1)
    i_to_x[i] = x-1

xy.sort(key=lambda x: x[1])

uf = UnionFind(N)

max_x = N-1
x_set = set()
hist_x_min = N
for x, y in xy:
    x_set.add(x)
    if x == max_x:
        while max_x in x_set:
            max_x -= 1
    else:
        uf.union(x, max_x)
#         print(x, max_x)
        if x < hist_x_min:
            for x_ in range(x+1, hist_x_min):
                uf.union(x, x_)
#                 print(x, x_)
    hist_x_min = min(hist_x_min, x)
#     print(max_x)
# print(uf)

ans = [0] * N
for i in range(N):
    ans[i] = uf.size(uf.find(i_to_x[i]))
print('\n'.join(map(str, ans)))

Submission status: Accepted

Solution code:
N = int(input())
X = [tuple(map(int,input().split())) for _ in range(N)]

par = [-1 for _ in range(N)]
def find(x):
        if par[x] < 0:
            return x
        else:
            par[x] = find(par[x]) #経路圧縮
            return par[x]
def same(x,y):
        return find(x) == find(y)
def unite(x,y):
        x = find(x)
        y = find(y)
        #print(x, y)
        if x == y:
            return 0
        else:
          if par[x] > par[y]:
            x,y = y,x
          par[x] += par[y]
          par[y] = x
def size(x):
        return -par[find(x)]
    


y_list = [0 for _ in range(N)]
for x, y in X:
  y_list[x-1] = y-1
#print(y_list)

tp = N
rest = N
for i in range(N):
  y = y_list[i]
  if y > tp:
    continue
  rest -= 1
  #print(i,rest)
  if i + rest < N-1: #残っている時
    unite(y, tp)
  #print(i, y, rest, tp, par)
  j = y + 1
  while j < tp:
    rest -= 1
    unite(y, j) 
    #print(y, j, par)
    j += 1
  tp = y
#print(par)  
for x, y in X:
  print(size(y-1))

Submission status: Accepted

Solution code:
import sys
def input():
	return sys.stdin.buffer.readline()[:-1]

class UnionFind():
	def __init__(self, size):
		self.table = [-1 for _ in range(size)]
		self.size = [1 for _ in range(size)]

	def find(self, x):
		while self.table[x] >= 0:
			if self.table[self.table[x]] >= 0:
				self.table[x] = self.table[self.table[x]]
			x = self.table[x]
		return x

	def unite(self, x, y):
		s1 = self.find(x)
		s2 = self.find(y)
		if s1 != s2:
			if self.table[s1] > self.table[s2]:
				self.table[s2] = s1
				self.table[s1] -= 1
				self.size[s1] += self.size[s2]
				self.size[s2] = 0
			else:
				self.table[s1] = s2
				self.table[s2] -= 1
				self.size[s2] += self.size[s1]
				self.size[s1] = 0
		return

n = int(input())
d = [list(map(int, input().split())) + [i] for i in range(n)]
d = [[x-1, y-1, i] for x, y, i in d]
d.sort()
uf = UnionFind(n)
cum = [0 for _ in range(n)]
for i in range(n-1):
	if d[i][1] < d[i+1][1]:
		cum[d[i][1]] += 1
		cum[d[i+1][1]] -= 1
for i in range(n):
	if i > 0:
		cum[i] += cum[i-1]
	if cum[i] > 0:
		uf.unite(i, i+1)

ans = [0 for _ in range(n)]
for i in range(n):
	ans[d[i][2]] = uf.size[uf.find(d[i][1])]

print(*ans, sep="\n")

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter

N=int(input())
T=[list(map(int,input().split()))+[i] for i in range(N)]

YtoN=[-1]*(N+1)
for x,y,n in T:
    YtoN[y]=n

T.sort(key=itemgetter(0))
MAX=N
MAXUSE=0
MIN=10**6
left=0

ANS=[-1]*N

for i in range(N):
    x,y,n=T[i]

    if y==MAX:
        MAXUSE=1
        
    MIN=min(y,MIN)

    #print(i,MAX,MIN,MAXUSE,left)

    if MAXUSE==1 and MAX-MIN==i-left:
        for j in range(left,i+1):
            ANS[T[j][2]]=MAX-MIN+1

        MAX=MIN-1
        MAXUSE=0
        left=i+1

for ans in ANS:
    print(ans)

Submission status: Accepted

Solution code:
import sys
import bisect
from collections import deque

input = sys.stdin.readline
N = int(input())
xy = sorted([[i] + list(map(int, input().split())) for i in range(N)], key=lambda x: x[1])


class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

uf = UnionFind(N)
ys = deque([(xy[0][2], xy[0][0])])  # union毎に最小のyのみ保持する
for i, x, y in xy[1:]:
    if ys[0][0] >= y:
        ys.appendleft((y, i))
        continue
    miny, minj = ys[0]
    while len(ys)>0:
        y_, j = ys.popleft()
        if y_ >= y:
            ys.appendleft((y_, j))
            break
        uf.union(i, j)
    ys.appendleft((miny, minj))
for i in range(N):
    print(uf.size(i))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from operator import itemgetter

class UF():
    def __init__(self, num):
        self.par = [-1]*num
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            stack = []
            while self.par[x] >= 0:
                stack.append(x)
                x = self.par[x]
            for xi in stack:
                self.par[xi] = x
            return x
    
    def union(self, x, y):
        rx = self.find(x)
        ry = self.find(y)
        if rx != ry:
            if self.par[rx] > self.par[ry]:
                rx, ry = ry, rx
            self.par[rx] += self.par[ry]
            self.par[ry] = rx
        return rx

N = int(readline())
XY = []
for i in range(N):
    x, y = map(int, readline().split())
    XY.append((i, x, y))

_, _, Y = map(list, zip(*XY))

XY.sort(key = itemgetter(1))

T = UF(N)

stack = []
for i, _, y in XY:
    my = i
    while stack and Y[stack[-1]] < y:
        if Y[stack[-1]] < Y[my]:
            my = stack[-1]
        T.union(stack.pop(), i)
    stack.append(my)
ans = [-T.par[T.find(i)] for i in range(N)]
    
print('\n'.join(map(str, ans)))

Submission status: Accepted

Solution code:
class SortedList:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        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):
        """Build a fenwick tree instance."""
        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):
        """Update `fen_tree[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):
        """Return `sum(_fen_tree[: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):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _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):
        """Delete value at the given `(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):
        """Return an index pair that corresponds to the first position of `value` in the sorted list."""
        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):
        """Return an index pair that corresponds to the last position of `value` in the sorted list."""
        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):
        """Add `value` to sorted list."""
        _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):
        """Remove `value` from sorted list if it is a member."""
        _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):
        """Remove `value` from sorted list; `value` must be a member."""
        _len = self._len
        self.discard(value)
        if _len == self._len:
            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):
        """Remove and return value at `index` in sorted list."""
        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):
        """Return the first index to insert `value` in the sorted list."""
        pos, idx = self._loc_left(value)
        return self._fen_query(pos) + idx

    def bisect_right(self, value):
        """Return the last index to insert `value` in the sorted list."""
        pos, idx = self._loc_right(value)
        return self._fen_query(pos) + idx

    def count(self, value):
        """Return number of occurrences of `value` in the sorted list."""
        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):
        """Return the size of the sorted list."""
        return self._len

    def __getitem__(self, index):
        """Lookup value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """Remove value at `index` from sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __contains__(self, value):
        """Return true if `value` is an element of the sorted list."""
        _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 an iterator over the sorted list."""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """Return a reverse iterator over the sorted list."""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """Return string representation of sorted list."""
        return 'SortedList({0})'.format(list(self))

class DisjointSetUnion:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.num_sets = n

    def find(self, a):
        acopy = a
        while a != self.parent[a]:
            a = self.parent[a]
        while acopy != a:
            self.parent[acopy], acopy = a, self.parent[acopy]
        return a

    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a != b:
            if self.size[a] < self.size[b]:
                a, b = b, a

            self.num_sets -= 1
            self.parent[b] = a
            self.size[a] += self.size[b]

    def set_size(self, a):
        return self.size[self.find(a)]

    def __len__(self):
        return self.num_sets

import sys
input = sys.stdin.readline

N = int(input())
p = []
order = []
for i in range(N):
    a, b = map(int, input().split())
    p.append((a-1,b-1))
    order.append(a-1)
p.sort()
rev = [0] * N
for a, b in p:
    rev[b] = a

UF = DisjointSetUnion(N)
cl = SortedList()

for x,v in p:
    ind = cl.bisect_left(v)
    rem = []
    for i in range(ind):
        UF.union(x, rev[cl[i]])
        
    cl.add(v)
    for i in range(ind):
        cl.remove(cl[1])

for i in order:
    print(UF.set_size(i))

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
X, Y = [], []
for _ in range(N):
    x, y = map(int, input().split())
    X.append(x-1)
    Y.append(y-1)

IX = [0] * N
for i, x in enumerate(X):
    IX[x] = i

YY = [Y[IX[i]] for i in range(N)]
mi = N
L = []
I = [0] * N
T = []
for i, y in enumerate(YY):
    mi = min(mi, y)
    T.append(i)
    I[i] = len(L)
    if mi == N - 1 - i:
        L.append(T)
        T = []
if len(T):
    L.append(T)
print(*[len(L[I[X[i]]]) for i in range(N)], sep = "\n")

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.buffer.readline

n=int(readline())
x2i=[0]*n
i2y=[0]*n
for i in range(n):
	a,b=map(int,readline().split())
	x2i[n-a]=i
	i2y[i]=b-1

ans=[0]*n

pre=0
mx=0
for x in range(n):
	i=x2i[x]
	y=i2y[i]
	mx=max(mx,y)
	if mx==x:
		for p in range(pre,x+1):
			ans[x2i[p]]=x+1-pre
		pre=x+1

print(*ans,sep='\n')

Submission status: Runtime Error

Solution code:
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
# mod=1000000007
mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')



    
def solve():

    
    # for _ in range(ii()):

    n = ii()

    sz = [1]*n
    par = [i for i in range(n)]

    def find(u):
        while(par[u] != u):
            par[u] = fin(par[u])
        return par[u]

    def merge(u,v):

        u = find(u)
        v = find(v)
        if u != v:
            if sz[u] > sz[v]:
                u,v=v,u
            sz[v] += sz[u]
            par[u] = v


    pts = []


    for i in range(n):
        x,y = mi()
        pts.append([x,y,i])

    pts.sort()
    for i in range(n):
        for j in range(i):
            if pts[j][1] < pts[i][1]:
                merge(pts[j][2],pts[i][2])

   
    for i in range(n):
        print(sz[par[i]])







        
if __name__ =="__main__":

    
    if path.exists('input.txt'):
        sys.stdin=open('input.txt', 'r')
        sys.stdout=open('output.txt','w')
    else:
        input=sys.stdin.readline
    solve()

Submission status: Runtime Error

Solution code:
a = []
b = []
number = []


hello = input()
for i in range(0,int(hello)):
    temp = input()
    temp.split(' ')
    a.append(int(temp[0]))
    b.append(int(temp[1]))
    number.append(1)

for i in range(0, int(hello)):
    for j in range(0, int(hello)):
        if i != j:
            if a[i]>a[j] and b[i]>b[j]:
                number[i] = number[i] + 1
            elif a[i]<a[j] and b[i]<b[j]:
                number[i] = number[i] + 1

for i in range(0, int(hello)):
    print(number[i])

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline

class Unionfind:
     
    def __init__(self,n):
        self.uf = [-1]*n
 
    def find(self,x):
        if self.uf[x] < 0:
            return x
        else:
            self.uf[x] = self.find(self.uf[x])
            return self.uf[x]
 
    def same(self,x,y):
        return self.find(x) == self.find(y)
 
    def union(self,x,y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if self.uf[x] > self.uf[y]:
            x,y = y,x
        self.uf[x] += self.uf[y]
        self.uf[y] = x
        return True
 
    def size(self,x):
        x = self.find(x)
        return -self.uf[x]


n = int(input())
xy = [[map(int,input().split()),i] for i in range(n)]
xy2 = sorted(xy)
u = Unionfind(n)

l = []
for x,y,ind in xy2:
    M = y
    le = ind
    while l and xy[l[-1]][1] < y:
        v = l.pop()
        if M > xy[v][1]:
            M = xy[v][1]
            le = v
        u.union(ind,v)
    l.append(le)
for i in range(n):
    print(u.size(i))

Submission status: Runtime Error

Solution code:
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.parents = [-1] * n

  def find(self, x):
    if self.parents[x] < 0:
      return x
    else:
      self.parents[x] = self.find(self.parents[x])
    return self.parents[x]

  def union(self, x, y):
    x = self.find(x)
    y = self.find(y)

    if x == y:
      return

    if self.parents[x] > self.parents[y]:
      x, y = y, x

    self.parents[x] += self.parents[y]
    self.parents[y] = x

  def same(self, x, y):
    return self.find(x) == self.find(y)

  def roots(self):
    return [i for i, x in enumerate(self.parents) if x < 0]

  def num_roots(self):
    return len([i for i, x in enumerate(self.parents) if x < 0])

  def members(self, x):
    root = self.find(x)
    return [i for i in range(self.n) if self.find(i) == root]

  def num_members(self,x):
    return abs(self.parents[self.find(x)])

  def __str__(self):
    return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

import sys,os,io
input = sys.stdin.readline
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
N = int(input())
A = [list(map(int, input().split()))+[i] for i in range(N)]
uf = UnionFind(N)
ans = [1]*N
A.sort()
Y = [(i,y) for x,y,i in A]
from heapq import *
heap = []
for u,y in Y:
  for _ in range(len(heap)):
    y1,v = heappop(heap)
    if y<y1:
      heappush(heap,(y1,v))
      break
    if uf.parents[v]>=0:
      continue
    uf.union(u,v)
    if uf.parents[v]<0:
      deq.append(v)
  if uf.parents[u]<0:
    heappush(heap,(y,u))
for i in range(N):
  ans[i] = uf.num_members(i)
print(*ans, sep='\n')

Submission status: Runtime Error

Solution code:
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.parents = [-1] * n
    self.min_y = [N]*n

  def find(self, x):
    if self.parents[x] < 0:
      return x
    else:
      self.parents[x] = self.find(self.parents[x])
    return self.parents[x]

  def union(self, x, y):
    x = self.find(x)
    y = self.find(y)

    if x == y:
      return

    if self.parents[x] > self.parents[y]:
      x, y = y, x

    self.parents[x] += self.parents[y]
    self.min_y[x] = min(self.min_y[x],self.min_y[y])
    self.parents[y] = x

  def same(self, x, y):
    return self.find(x) == self.find(y)

  def roots(self):
    return [i for i, x in enumerate(self.parents) if x < 0]

  def num_roots(self):
    return len([i for i, x in enumerate(self.parents) if x < 0])

  def members(self, x):
    root = self.find(x)
    return [i for i in range(self.n) if self.find(i) == root]

  def num_members(self,x):
    return abs(self.parents[self.find(x)])

  def __str__(self):
    return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

import sys,os,io
input = sys.stdin.readline
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
N = int(input())
A = [list(map(int, input().split()))+[i] for i in range(N)]
uf = UnionFind(N)
uf.min_y = [y for x,y,i in A]
ans = [1]*N
A.sort()
Y = [(i,y) for x,y,i in A]
from heapq import *
heap = []
for u,y in Y:
  for _ in range(len(heap)):
    y1,v = heappop(heap)
    if y<y1:
      heappush(heap,(y1,v))
      break
    if uf.parents[v]>=0:
      continue
    uf.union(u,v)
    if uf.parents[v]<0:
      deq.append(v)
  if uf.parents[u]<0:
    heappush(heap,(y,u))
for i in range(N):
  ans[i] = uf.num_members(i)
print(*ans, sep='\n')