def read_a(n, m):
    A = []
    for _ in range(0, n):
        A.append([int(x) for x in input().split()])

    return A

def read_b(m):
    B = []
    for _ in range(0, m):
        B.append(int(input()))

    return B

def multiply(A, B):
    C = []
    for a in A:
        C.append(sum(map(lambda x, y:x*y, a, B)))

    return C

def main():
    n, m = [int(x) for x in input().split()]

    A = read_a(n, m)
    B = read_b(m)
    C = multiply(A, B)

    print("\n".join([str(x) for x in C]))

if __name__ == '__main__':
    main()

def main():

    m, n = tuple(map(int, input().split()))
    a = [[0 for j in range(n)] for i in range(m)]
    b = [0 for j in range(n)]
    c = [0 for i in range(m)]

    for i in range(m):
        tmplst = list(map(int, input().split()))
        for j in range(n):
            a[i][j] = tmplst[j]

    for j in range(n):
        b[j] = int(input())

    for i in range(m):
        for j in range(n):
            c[i] += a[i][j] * b[j]
        print(c[i])

if __name__ == '__main__':
    main()

Matrix Vector Multiplication

Write a program which reads a $ n \times m$ matrix $A$  and a $m \times 1$ vector $b$, and prints their product $Ab$.

  A column vector with <var>m</var> elements is represented by the following equation.

\[
  b = \left(
    \begin{array}{c}
      b_1  \\
      b_2  \\
      : \\
      b_m \\
    \end{array}
  \right)
\]

  A $n \times m$ matrix with $m$ column vectors, each of which consists of $n$ elements, is represented by the following equation.

\[
  A = \left(
    \begin{array}{cccc}
      a_{11} & a_{12} & ... & a_{1m} \\
      a_{21} & a_{22} & ... & a_{2m} \\
       :    &   :   &  :  &  : \\
      a_{n1} & a_{n2} & ... & a_{nm} \\
    \end{array}
  \right)
\]

  $i$-th element of a $m \times 1$ column vector $b$ is represented by $b_i$ ($i = 1, 2, ..., m$), and the element in $i$-th row and $j$-th column of a matrix $A$ is represented by $a_{ij}$ ($i = 1, 2, ..., n,$  $j = 1, 2, ..., m$).

The product of a $n \times m$ matrix $A$ and a $m \times 1$ column vector $b$ is a $n \times 1$ column vector $c$, and $c_i$ is obtained by the following formula:

\[
c_i = \sum_{j=1}^m a_{ij}b_j  = a_{i1}b_1 + a_{i2}b_2 + ... + a_{im}b_m
\]

Input

  In the first line, two integers $n$ and $m$ are given. In the following $n$ lines, $a_{ij}$ are given separated by a single space character. In the next $m$ lines, $b_i$ is given in a line.

Output

  The output consists of $n$ lines. Print $c_i$ in a line.

Constraints

$1 \leq n, m \leq 100$

$0 \leq b_i, a_{ij} \leq 1000$

Sample Input

3 4
1 2 0 1
0 3 0 1
4 1 1 0
1
2
3
0

Sample Output

5
6
9


n,m = map(int,input().split())
a = []; b= [];
for i in range(m): a.append(list(map(int,input().split())))
for i in range(n): b.append(int(input()))
for i in range(n):
    c = 0
    for j in range(m):
        c += a[i][j]*b[i]
    print(c)


def main():

    TaroScore = HanaScore = 0
    n = int(input())
    for _ in range(n):
        [Taro, Hana] = list(input().lower().split())

        lenT = len(Taro)
        lenH = len(Hana)
        lenMin = min(lenT, lenH)

        if Taro == Hana:
            TaroScore += 1
            HanaScore += 1

        else:
            for i in range(lenMin+1):
                if Taro == '':
                    HanaScore += 3
                    break
                elif Hana == '':
                    TaroScore += 3
                    break
                elif ord(Taro[0]) > ord(Hana[0]):
                    TaroScore += 3
                    break
                elif ord(Taro[0]) < ord(Hana[0]):
                    HanaScore += 3
                    break
                else:
                    Taro = Taro[1:]
                    Hana = Hana[1:]

    print(TaroScore, HanaScore)

if __name__ == '__main__':
    main()

def main():
    n = int(input())
    taro, hanako = 0, 0
    for _ in range(n):
        cards = input().split()
        if cards[0] == cards[1]:
            taro += 1
            hanako += 1
        elif cards[0] != sorted(cards)[0]:
            taro += 3
        else:
            hanako += 3
    print(taro, hanako)

if __name__ == '__main__':
    main()

Card Game

  Taro and Hanako are playing card games. They have <var>n</var> cards each, and they compete <var>n</var> turns. At each turn Taro and Hanako respectively puts out a card.
  The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner obtains 3 points. In the case of a draw, they obtain 1 point each.

  Write a program which reads a sequence of cards Taro and Hanako have and reports the final scores of the game.

Input

  In the first line, the number of cards <var>n</var> is given. In the following <var>n</var> lines, the cards for <var>n</var> turns are given respectively. For each line, the first string represents the Taro's card and the second one represents Hanako's card.

Constraints

<var>n</var> ≤ 1000

The length of the string ≤ 100

Output

  Print the final scores of Taro and Hanako respectively. Put a single space character between them.

Sample Input

3
cat dog
fish fish
lion tiger

Sample Output

1 7


def main():

    TaroScore = HanaScore = 0
    n = int(input())
    for _ in range(n):
        [Taro, Hana] = list(input().lower().split())

        lenT = len(Taro)
        lenH = len(Hana)
        lenMin = min(lenT, lenH)

        if Taro == Hana:
            TaroScore += 1
            HanaScore += 1
        else:
            for i in range(lenMin):
                if ord(Taro[i]) > ord(Hana[i]):
                    TaroScore += 3
                    break
                elif ord(Taro[i]) < ord(Hana[i]):
                    HanaScore += 3
                    break
                else:
                    pass

    print(TaroScore, HanaScore)

if __name__ == '__main__':
    main()


n = int(input())
items = []
for i in range(n):
    val, weight, type, date, name = input().split(' ')
    items.append([int(val), int(weight), type, int(date), name])

items = sorted(items)
for item in items:
    print(' '.join(list(map(str, item))))

# coding=utf-8

N = int(input())
goods = []
for i in range(N):
    a, b, c, d, e = input().split()
    goods.append((int(a), int(b), c, int(d), e))
goods.sort()
[print(' '.join(map(str, x))) for x in goods]

Sorting Tuples

  Write a program which reads $n$ items and sorts them. Each item has attributes $\{value, weight, type, date, name\}$ and they are represented by $\{$ integer, integer, upper-case letter, integer, string $\}$ respectively. Sort the items based on the following priorities.

first by value (ascending)

in case of a tie, by weight (ascending)

in case of a tie, by type (ascending in lexicographic order)

in case of a tie, by date (ascending)

in case of a tie, by name (ascending in lexicographic order)

Input

  The input is given in the following format.

$n$
$v_0 \; w_0 \; t_0 \; d_0 \; s_0$
$v_1 \; w_1 \; t_1 \; d_1 \; s_1$
:
$v_{n-1} \; w_{n-1} \; t_{n-1} \; d_{n-1} \; s_{n-1}$

  In the first line, the number of items $n$. In the following $n$ lines, attributes of each item are given. $v_i \; w_i \; t_i \; d_i \; s_i$ represent value, weight, type, date and name of the $i$-th item respectively.

Output

  Print attributes of each item in order. Print an item in a line and adjacency attributes should be separated by a single space.

Constraints

$1 \leq n \leq 100,000$

$0 \leq v_i \leq 1,000,000,000$

$0 \leq w_i \leq 1,000,000,000$

$t_i$ is a upper-case letter

$0 \leq d_i \leq 2,000,000,000,000$

$1 \leq $ size of $s_i \leq 20$

$s_i \ne s_j$ if $(i \ne j)$

Sample Input 1

5
105 24 C 1500000000000 white
100 23 C 1500000000000 blue
105 23 A 1480000000000 pink
110 25 B 1500000000000 black
110 20 A 1300000000000 gree

Sample Output 1

100 23 C 1500000000000 blue
105 23 A 1480000000000 pink
105 24 C 1500000000000 white
110 20 A 1300000000000 gree
110 25 B 1500000000000 black


n = int(input())
items = [input().split(' ') for i in range(n)]

items = sorted(items)
for item in items:
    print(' '.join(item))


from enum import Enum
import math

class Color(Enum):
    BLACK = 0
    RED = 1

    @staticmethod
    def flip(c):
        return [Color.RED, Color.BLACK][c.value]

class RedBlackBinarySearchTree:
    """Red Black Binary Search Tree with range, min, max.
    """

    class Node:
        __slots__ = ('key', 'left', 'right', 'count', 'color')

        def __init__(self, key):
            self.key = key
            self.left = None
            self.right = None
            self.count = 0
            self.color = Color.RED

        def __str__(self):
            if self.color == Color.RED:
                key = '*{}'.format(self.key)
            else:
                key = '{}'.format(self.key)
            return "{}[{}] ({}, {})".format(key, self.count,
                                            self.left, self.right)

    def __init__(self):
        self.root = None

    def put(self, key):
        def _put(node):
            if node is None:
                node = self.Node(key)
            if node.key > key:
                node.left = _put(node.left)
            elif node.key < key:
                node.right = _put(node.right)

            node = self._restore(node)

            node.count = self._size(node.left) + self._size(node.right) + 1
            return node

        self.root = _put(self.root)
        self.root.color = Color.BLACK

    def _is_red(self, node):
        if node is None:
            return False
        else:
            return node.color == Color.RED

    def _is_black(self, node):
        if node is None:
            return False
        else:
            return node.color == Color.BLACK

    def _is_2node(self, node):
        if node is None:
            return False
        elif self._is_red(node):
            return False
        else:
            return (self._is_black(node) and
                    not self._is_red(node.left) and
                    not self._is_red(node.right))

    def _is_34node(self, node):
        if node is None:
            return False
        elif self._is_red(node):
            return True
        else:
            return (self._is_black(node) and
                    self._is_red(node.left) and
                    not self._is_red(node.right))

    def _rotate_left(self, node):
        x = node.right
        node.right = x.left
        x.left = node
        x.color = node.color
        node.color = Color.RED
        node.count = self._size(node.left) + self._size(node.right) + 1
        return x

    def _rotate_right(self, node):
        x = node.left
        node.left = x.right
        x.right = node
        x.color = node.color
        node.color = Color.RED
        node.count = self._size(node.left) + self._size(node.right) + 1
        return x

    def _flip_colors(self, node):
        node.color = Color.flip(node.color)
        node.left.color = Color.flip(node.left.color)
        node.right.color = Color.flip(node.right.color)
        return node

    def __contains__(self, key):
        def _contains(node):
            if node is None:
                return False
            if node.key > key:
                return _contains(node.left)
            elif node.key < key:
                return _contains(node.right)
            else:
                return True
        return _contains(self.root)

    def delete(self, key):
        def _delete_from(node):
            if node is None:
                return None
            else:
                assert not self._is_2node(node)

                if node.key > key:
                    node = self._convert_left(node)
                    # print('_convert_left', node)
                    node.left = _delete_from(node.left)
                    node = self._restore(node)
                    # print('_restore', node)
                elif node.key < key:
                    node = self._convert_right(node)
                    # print('_convert_right', node)
                    node.right = _delete_from(node.right)
                    node = self._restore(node)
                    # print('_restore', node)
                else:
                    node = _remove(node)

            if node is not None:
                node.count = self._size(node.right) + self._size(node.left) + 1
            return node

        def _remove(node):
            if node.left is None:
                return None
            elif node.right is None:
                if self._is_red(node.left):
                    node.left.color = Color.BLACK
                return node.left
            else:
                node = self._convert_right(node)
                if node.key == key:
                    x = self._find_min(node.right)
                    node.key = x.key
                    node.right = self._delete_min(node.right)
                else:
                    # print(node)
                    node.right = _delete_from(node.right)
                node = self._restore(node)
                # print('min', x.key, 'node', node.key)
                return node

        if self.root is None:
            return
        # print('initial', self.root)
        if not self._is_red(self.root.left):
            self.root.color = Color.RED
        self.root = _delete_from(self.root)
        if self.root is not None:
            self.root.color = Color.BLACK

    def delete_max(self):
        if self.root is None:
            raise ValueError('remove max on empty tree')
        if self.root.left is None:
            self.root = None
            return
        if not self._is_red(self.root.left):
            self.root.color = Color.RED
        self.root = self._delete_max(self.root)
        self.root.color = Color.BLACK

    def _delete_max(self, node):
        if node.right is None:
            if self._is_red(node.left):
                node.left.color = Color.BLACK
            return node.left
        else:
            assert not self._is_2node(node)
            node = self._convert_right(node)
            node.right = self._delete_max(node.right)
            node = self._restore(node)
            return node

    def _convert_right(self, node):
        if self._is_2node(node.right):
            if self._is_2node(node.left):
                self._flip_colors(node)
            elif self._is_red(node.left) and self._is_2node(node.left.right):
                node = self._rotate_right(node)
                self._flip_colors(node.right)
            elif self._is_red(node.left):
                x = node.left.right
                node.left.right = x.left
                node.left, node.right, x.left, x.right = \
                    x.right, node.right.left, node.left, node.right
                x.right.left = node
                x.color = Color.BLACK
                node.color = Color.RED
                if self._is_red(x.left.right):
                    x.left.right.color = Color.BLACK
                node.count = (self._size(node.left) +
                              self._size(node.right) + 1)
                x.left.count = (self._size(x.left.left) +
                                self._size(x.left.right) + 1)
                node = x
            elif self._is_34node(node.left):
                x = node.left
                node.left, node.right, x.right = \
                    x.right, node.right.left, node.right
                x.right.left = node
                x.color = node.color
                if self._is_red(x.left):
                    x.left.color = Color.BLACK
                if self._is_black(x.right.left):
                    x.right.left.color = Color.RED
                node.count = (self._size(node.left) +
                              self._size(node.right) + 1)
                x.left.count = (self._size(x.left.left) +
                                self._size(x.left.right) + 1)
                node = x
        return node

    def delete_min(self):
        if self.root is None:
            raise ValueError('remove min on empty tree')
        if self.root.left is None:
            self.root = None
            return
        if not self._is_red(self.root.left):
            self.root.color = Color.RED
        self.root = self._delete_min(self.root)
        self.root.color = Color.BLACK

    def _delete_min(self, node):
        if node.left is None:
            return None
        else:
            node = self._convert_left(node)
            node.left = self._delete_min(node.left)
            node = self._restore(node)
            return node

    def _convert_left(self, node):
        if self._is_2node(node.left):
            if self._is_2node(node.right):
                self._flip_colors(node)
            elif self._is_34node(node.right):
                x = node.right.left
                node.right.left = x.right
                x.left, x.right, node.right = node, node.right, x.left
                x.color = node.color
                node.color = Color.BLACK
                node.left.color = Color.RED
                x.right.count = (self._size(x.right.left) +
                                 self._size(x.right.right) + 1)
                node = x
        return node

    def _restore(self, node):
        if self._is_red(node.right) and not self._is_red(node.left):
            node = self._rotate_left(node)
        if self._is_red(node.left) and self._is_red(node.left.left):
            node = self._rotate_right(node)
        if self._is_red(node.left) and self._is_red(node.right):
            node = self._flip_colors(node)

        node.count = self._size(node.left) + self._size(node.right) + 1
        return node

    def _is_balanced(self, node):
        def depth(node):
            if node is None:
                return 0
            left = depth(node.left)
            right = depth(node.right)
            if left != right:
                raise Exception('unbalanced')
            if self._is_black(node):
                return 1 + left
            else:
                return left

        if node is None:
            return True

        try:
            left = depth(node.left)
            right = depth(node.right)
            return left == right
        except Exception:
            return False

    @property
    def size(self):
        return self._size(self.root)

    def _size(self, node):
        if node is None:
            return 0
        else:
            return node.count

    @property
    def max(self):
        if self.root is None:
            raise ValueError('max on empty tree')
        return self._max(self.root)

    def _max(self, node):
        x = self._find_max(node)
        return x.key

    def _find_max(self, node):
        if node.right is None:
            return node
        else:
            return self._find_max(node.right)

    @property
    def min(self):
        if self.root is None:
            raise ValueError('min on empty tree')
        return self._min(self.root)

    def _min(self, node):
        x = self._find_min(node)
        return x.key

    def _find_min(self, node):
        if node.left is None:
            return node
        else:
            return self._find_min(node.left)

    def range(self, min_, max_):
        def _range(node):
            if node is None:
                return

            if node.key > max_:
                yield from _range(node.left)
            elif node.key < min_:
                yield from _range(node.right)
            else:
                yield from _range(node.left)
                yield node.key
                yield from _range(node.right)

        if min_ > max_:
            return
        yield from _range(self.root)

class BalancedBstSet:
    def __init__(self):
        self.bst = RedBlackBinarySearchTree()

    def add(self, key):
        self.bst.put(key)

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

    def delete(self, key):
        self.bst.delete(key)

    def range(self, a, b):
        for k in self.bst.range(a, b):
            yield k

    @property
    def count(self):
        return self.bst.size

    def __str__(self):
        return str(self.bst.root)

def run():
    q = int(input())
    s = BalancedBstSet()

    for _ in range(q):
        command, *value = [int(x) for x in input().split()]
        if command == 0:
            s.add(value[0])
            print(s.count)
        elif command == 1:
            if value[0] in s:
                print(1)
            else:
                print(0)
        elif command == 2:
            s.delete(value[0])
        elif command == 3:
            for i in s.range(*value):
                print(i)
        else:
            raise ValueError('invalid command')

if __name__ == '__main__':
    run()

# AOJ ITP2_7_C: Set: Range Search
# Python3 2018.6.24 bal4u

from bisect import bisect_left, bisect_right, insort_left
dict = {}
keytbl = []
cnt = 0
q = int(input())
for i in range(q):
	a = list(input().split())
	ki = int(a[1])
	if a[0] == '0':
		if ki not in dict:
			dict[ki] = 1
			cnt += 1
			insort_left(keytbl, ki)
		elif dict[ki] == 0:
			dict[ki] = 1
			cnt += 1
		print(cnt)
	elif a[0] == '1': print(dict[ki] if ki in dict else 0)
	elif a[0] == '2':
		if ki in dict:
			cnt -= dict[ki]
			dict[ki] = 0
	else:
		L = bisect_left (keytbl, int(a[1]))
		R = bisect_right(keytbl, int(a[2]), L)
		for j in range(L, R):
			if dict[keytbl[j]] == 1: print(keytbl[j])

Set: Range Search

  For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique.

insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation.

find($x$): Report the number of $x$ in $S$ (0 or 1).

delete($x$): Delete $x$ from $S$.

dump($L$, $R$): Print elements $x$ in $S$ such that $L \leq x \leq R$.

Input

  The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $x$

or

1 $x$

or

2 $x$

or

3 $L$ $R$

where the first digits 0, 1, 2 and 3 represent insert, find, delete and dump operations respectively.

Output

For each insert operation, print the number of elements in $S$.

For each find operation, print the number of specified elements in $S$.

For each dump operation, print the corresponding elements in ascending order. Print an element in a line.

Constraints

$1 \leq q \leq 200,000$

$0 \leq x \leq 1,000,000,000$

The total number of elements printed by dump operations does not exceed $1,000,000$

Sample Input 1

9
0 1
0 2
0 3
2 2
1 1
1 2
1 3
0 4
3 2 4

Sample Output 1

1
2
3
1
0
1
3
3
4


def binary(l,c):
    fst = 0
    last = len(l)
    mid = int(last/2)
    while fst < last:
        mid = int((fst+last) / 2)
        if last == mid:
            break
        elif fst == mid:
            break
        elif l[mid] >= c:
            last = mid
        elif l[mid] <= c:
            fst = mid
    if mid == 0:
        l.insert(mid,c)
    elif l[mid] < c:
        mid+=1
        l.insert(mid,c)

q = int(input())
S = []
a = []
for i in range(q):
    a.append(list(map(int,input().split())))

for i in range(q):
    if a[i][0] == 0:
        binary(S,a[i][1])
        print(len(S))
    elif a[i][0] == 1:
        if a[i][1] in S:
            print(1)
        else:
            print(0)
    elif a[i][0] == 2:
        if a[i][1] in S:
            S.remove(a[i][1])
    else:
        for b in range(len(S)):
            if S[b] >= a[i][1] and S[b] <= a[i][2]:
                print(S[b])


from fractions import Fraction
def prime(num):
    prime_list = []
    temp = num
    div = 2
    while temp > 1 and temp >= div ** 2:
        if temp % div == 0:
            prime_list.append(div)
            temp //= div
        else:
            div += 1
    if temp != 1:
        prime_list.append(temp)
    return prime_list

target = int(input())
prime_list = prime(target)
answer = target
# print(prime_list)
for p in set(prime_list):
    answer *= (1 - Fraction(1, p))
print(answer)

import math
from collections import defaultdict

def prime_factorize(n: int):
    prime_factors = defaultdict(int)

    for i in range(2, int(math.sqrt(n)) + 1):
        while True:
            div, mod = divmod(n, i)
            if mod == 0:
                prime_factors[i] += 1
                n = div
            else:
                break
        if n == 1:
            break
    if n != 1:
        prime_factors[n] = 1

    return prime_factors

def main():
   n = int(input())
   primes = prime_factorize(n)

   ret = 1
   for k, v in primes.items():
      ret *= pow(k, v) - pow(k, v-1)
   print(ret)
   return

main()

Euler's Phi Function

For given integer <var>n</var>, count the totatives of <var>n</var>, that is, the positive integers less than or equal to <var>n</var> that are relatively prime to <var>n</var>.

Input

<var>n</var>

An integer <var>n</var> (1 ≤ <var>n</var> ≤ 1000000000).

Output

The number of totatives in a line.

Sample Input 1

6

Sample Output 1

2

Sample Input 2

1000000

Sample Output 2

400000


input = int(input())
buf = input
result = 1
for i in range(2,input):
    if buf%i==0:
        result *= (1 - 1/i)
    while buf%i==0:
        buf /= i
result *= input
print(int(result))


n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
b.reverse()
c=[0]*(n+1)
for i in a:
  c[i]+=1
for i in b:
  c[i]+=1
if n<max(c):
  print('No')
  exit(0)
l=0
while l<n and a[l]!=b[l]:
  l+=1
i=0
while l<n and a[l]==b[l]:
  while a[i]==b[l] or a[l]==b[i]:
    i+=1
  b[i],b[l]=b[l],b[i]
  l+=1
print('Yes')
print(' '.join([str(i) for i in b]))

#!/usr/bin/env python3
from collections import Counter
INF = 1e12

def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    lA = Counter(A)
    lB = Counter(B)
    if max(Counter(A+B).values()) > N:
        print('No')
        exit()

    C = [0] * (N + 1)
    D = [0] * (N + 1)
    for i in range(N):
        C[i + 1] = lA[i + 1] + C[i]
        D[i + 1] = lB[i + 1] + D[i]
    shift = - INF
    for i in range(1, N + 1):
        shift = max(shift, C[i] - D[i - 1])
    print('Yes')
    ans = (B + B + B)[N-shift:2*N-shift]
    print(' '.join([str(a) for a in ans]))

if __name__ == "__main__":
    main()

Score : <var>600</var> points

Problem Statement

Given are two sequences <var>A</var> and <var>B</var>, both of length <var>N</var>.
<var>A</var> and <var>B</var> are each sorted in the ascending order.
Check if it is possible to reorder the terms of <var>B</var> so that for each <var>i</var> (<var>1 \leq i \leq N</var>) <var>A_i \neq B_i</var> holds, and if it is possible, output any of the reorderings that achieve it.

Constraints

<var>1\leq N \leq 2 \times 10^5</var>

<var>1\leq A_i,B_i \leq N</var>

<var>A</var> and <var>B</var> are each sorted in the ascending order.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>\cdots</var> <var>A_N</var>
<var>B_1</var> <var>B_2</var> <var>\cdots</var> <var>B_N</var>

Output

If there exist no reorderings that satisfy the condition, print No.

If there exists a reordering that satisfies the condition, print Yes on the first line.
After that, print a reordering of <var>B</var> on the second line, separating terms with a whitespace.

If there are multiple reorderings that satisfy the condition, you can print any of them.

Sample Input 1

6
1 1 1 2 2 3
1 1 1 2 2 3

Sample Output 1

Yes
2 2 3 1 1 1

Sample Input 2

3
1 1 2
1 1 3

Sample Output 2

No

Sample Input 3

4
1 1 2 3
1 2 3 3

Sample Output 3

Yes
3 3 1 2


#!/usr/bin/env python3
from collections import Counter
INF = 1e12

def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    lA = Counter(A)
    lB = Counter(B)
    if max(lA.values()) + max(lB.values()) > N:
        print('No')
        exit()

    C = [0] * (N + 1)
    D = [0] * (N + 1)
    for i in range(N):
        C[i + 1] = lA[i + 1] + C[i]
        D[i + 1] = lB[i + 1] + D[i]
    shift = - INF
    for i in range(1, N + 1):
        shift = max(shift, C[i] - D[i - 1])
    print('Yes')
    ans = (B + B + B)[shift + N:shift + 2*N]
    print(' '.join([str(a) for a in ans]))

if __name__ == "__main__":
    main()


import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

class DisjointSetUnion:
    def __init__(self, n):
        self.n = n
        self.par = [-1] * n
        self.rank = [0] * n

    def root(self, x):
        if self.par[x] == -1:
            return x
        else:
            self.par[x] = self.root(self.par[x])
            return self.par[x]

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

    def unite(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            x, y = y, x
        if self.rank[x] == self.rank[y]:
            self.rank[x] += 1
        self.par[y] = x
        return

if __name__ == '__main__':
    n, q = map(int, readline().split())
    dsu = DisjointSetUnion(n)

    for i in range(q):
        t, u, v = map(int, readline().split())

        if t:
            print(int(dsu.same(u, v)))
        else:
            dsu.unite(u, v)

class DisjointSetUnion:
    def __init__(self, n):
        self.n = n
        self.par = [-1] * n
        self.rank = [0] * n

    def root(self, x):
        if self.par[x] == -1:
            return x
        else:
            self.par[x] = self.root(self.par[x])
            return self.par[x]

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

    def unite(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            x, y = y, x
        if self.rank[x] == self.rank[y]:
            self.rank[x] += 1
        self.par[y] = x
        return

if __name__ == '__main__':
    n, q = map(int, input().split())
    dsu = DisjointSetUnion(n)

    for i in range(q):
        t, u, v = map(int, input().split())

        if t:
            print(int(dsu.same(u, v)))
        else:
            dsu.unite(u, v)

Score : <var>100</var> points

Problem Statement

You are given an undirected graph with <var>N</var> vertices and <var>0</var> edges. Process <var>Q</var> queries of the following types.

0 u v: Add an edge <var>(u, v)</var>.

1 u v: Print <var>1</var> if <var>u</var> and <var>v</var> are in the same connected component, <var>0</var> otherwise.

Constraints

<var>1 \leq N \leq 200,000</var>

<var>1 \leq Q \leq 200,000</var>

<var>0 \leq u_i, v_i \lt N</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>Q</var>
<var>t_1</var> <var>u_1</var> <var>v_1</var>
<var>t_2</var> <var>u_2</var> <var>v_2</var>
:
<var>t_Q</var> <var>u_Q</var> <var>v_Q</var>

出力

For each query of the latter type, print the answer.

Sample Input 1

4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3

Sample Output 1

0
1
0
1


def find(u, tree_root):
    tree_root[u] = u if u == tree_root[u] else find(tree_root[u], tree_root)
    return tree_root[u]

def main():
    n, q = map(int, input().split())
    tree_root = list(range(n))
    for i in range(q):
        t, u, v = map(int, input().split())
        u_root, v_root = find(u, tree_root), find(v, tree_root)
        if t:
            print(1 if u_root == v_root else 0)
        else:
            tree_root[u] = v_root

if __name__ == "__main__":
    main()


import sys
from collections.abc import Iterable

def read():
    return sys.stdin.buffer.readline().rstrip()

class FenwickTree:
    def __init__(self, arg):
        if isinstance(arg, int):
            self._n = arg
            self._a = [0] * arg
        elif isinstance(arg, Iterable):
            a = list(arg)
            self._n = len(a)
            self._a = [0] * self._n
            self.set(a)

    def set(self, a):
        for i, ai in enumerate(a):
            self.add(i, ai)

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

    def update(self, i, x):
        self.add(i, x - self.sum(i, i + 1))

    def sum(self, l, r):
        return self._sum(r) - self._sum(l)

    def _sum(self, r):
        s = 0
        while r > 0:
            s += self._a[r - 1]
            r -= r & -r
        return s

def main():
    n, q = map(int, read().split())
    fw = FenwickTree(map(int, read().split()))
    for _ in range(q):
        query = [int(i) for i in read().split()]
        if query[0] == 0:
            fw.add(query[1], query[2])
        else:
            print(fw.sum(query[1], query[2]))

if __name__ == '__main__':
    main()

import sys

def read():
    return sys.stdin.buffer.readline().rstrip()

class FenwickTree:
    def __init__(self, n):
        self._n = n
        self._a = [0] * n

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

    def sum(self, l, r):
        return self._sum(r) - self._sum(l)

    def _sum(self, r):
        s = 0
        while r > 0:
            s += self._a[r - 1]
            r -= r & -r
        return s

def main():
    n, q = map(int, read().split())
    fw = FenwickTree(n)
    for i, ai in enumerate(map(int, read().split())):
        fw.add(i, ai)
    for _ in range(q):
        query = [int(i) for i in read().split()]
        if query[0] == 0:
            fw.add(query[1], query[2])
        else:
            print(fw.sum(query[1], query[2]))

if __name__ == '__main__':
    main()

Score : <var>100</var> points

Problem Statement

You are given an array <var>a_0, a_1, ..., a_{N-1}</var> of length <var>N</var>. Process <var>Q</var> queries of the following types.

0 p x: <var>a_p \gets a_p + x</var>

1 l r: Print <var>\sum_{i = l}^{r - 1}{a_i}</var>.

Constraints

<var>1 \leq N, Q \leq 500,000</var>

<var>0 \leq a_i, x \leq 10^9</var>

<var>0 \leq p < N</var>

<var>0 \leq l_i < r_i \leq N</var>

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>Q</var>
<var>a_0</var> <var>a_1</var> ... <var>a_{N - 1}</var>
<var>\textrm{Query}_0</var>
<var>\textrm{Query}_1</var>
:
<var>\textrm{Query}_{Q - 1}</var>

Output

For each query of the latter type, print the answer.

Sample Input 1

5 5
1 2 3 4 5
1 0 5
1 2 4
0 3 10
1 0 5
1 0 3

Sample Output 1

15
7
25
6


import sys

class Bit:
    def __init__(self, n, arr):
        self.size = n
        self.tree = [0] + arr
        for i in range(1, n):
            if i + (i & -i) < n:
                self.tree[i + (i & -i)] += self.tree[i]

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

    def range_sum(self, l, r):
        return self.sum(r) - self.sum(l)

def main():
    n, q = map(int, sys.stdin.buffer.readline().split())
    bit = Bit(n, list(map(int, sys.stdin.buffer.readline().split())))
    for x in sys.stdin.buffer.readlines():
        q, p, x = map(int, x.split())
        if q:
            print(bit.range_sum(p, x))
        else:
            bit.add(p+1, x)

if __name__ == "__main__":
    main()


# TODO: メモリリーク確認
# TODO: __repr__ を書く

code_scc_graph = r"""
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

// 元のライブラリの private を剥がした

// >>> AtCoder >>>

#ifndef ATCODER_SCC_HPP
#define ATCODER_SCC_HPP 1

#include <algorithm>

#ifndef ATCODER_INTERNAL_SCC_HPP
#define ATCODER_INTERNAL_SCC_HPP 1

#include <algorithm>
#include <utility>
#include <vector>

namespace atcoder {
namespace internal {

template <class E> struct csr {
    std::vector<int> start;
    std::vector<E> elist;
    csr(int n, const std::vector<std::pair<int, E>>& edges)
        : start(n + 1), elist(edges.size()) {
        for (auto e : edges) {
            start[e.first + 1]++;
        }
        for (int i = 1; i <= n; i++) {
            start[i] += start[i - 1];
        }
        auto counter = start;
        for (auto e : edges) {
            elist[counter[e.first]++] = e.second;
        }
    }
};

// Reference:
// R. Tarjan,
// Depth-First Search and Linear Graph Algorithms
struct scc_graph {
  public:
    scc_graph(int n) : _n(n) {}

    int num_vertices() { return _n; }

    void add_edge(int from, int to) { edges.push_back({from, {to}}); }

    // @return pair of (# of scc, scc id)
    std::pair<int, std::vector<int>> scc_ids() {
        auto g = csr<edge>(_n, edges);
        int now_ord = 0, group_num = 0;
        std::vector<int> visited, low(_n), ord(_n, -1), ids(_n);
        visited.reserve(_n);
        auto dfs = [&](auto self, int v) -> void {
            low[v] = ord[v] = now_ord++;
            visited.push_back(v);
            for (int i = g.start[v]; i < g.start[v + 1]; i++) {
                auto to = g.elist[i].to;
                if (ord[to] == -1) {
                    self(self, to);
                    low[v] = std::min(low[v], low[to]);
                } else {
                    low[v] = std::min(low[v], ord[to]);
                }
            }
            if (low[v] == ord[v]) {
                while (true) {
                    int u = visited.back();
                    visited.pop_back();
                    ord[u] = _n;
                    ids[u] = group_num;
                    if (u == v) break;
                }
                group_num++;
            }
        };
        for (int i = 0; i < _n; i++) {
            if (ord[i] == -1) dfs(dfs, i);
        }
        for (auto& x : ids) {
            x = group_num - 1 - x;
        }
        return {group_num, ids};
    }

    std::vector<std::vector<int>> scc() {
        auto ids = scc_ids();
        int group_num = ids.first;
        std::vector<int> counts(group_num);
        for (auto x : ids.second) counts[x]++;
        std::vector<std::vector<int>> groups(ids.first);
        for (int i = 0; i < group_num; i++) {
            groups[i].reserve(counts[i]);
        }
        for (int i = 0; i < _n; i++) {
            groups[ids.second[i]].push_back(i);
        }
        return groups;
    }

  private:
    int _n;
    struct edge {
        int to;
    };
    std::vector<std::pair<int, edge>> edges;
};

}  // namespace internal

}  // namespace atcoder

#endif  // ATCODER_INTERNAL_SCC_HPP

#include <cassert>
#include <vector>

namespace atcoder {

struct scc_graph {
  public:
    scc_graph() : internal(0) {}
    scc_graph(int n) : internal(n) {}

    void add_edge(int from, int to) {
        int n = internal.num_vertices();
        assert(0 <= from && from < n);
        assert(0 <= to && to < n);
        internal.add_edge(from, to);
    }

    std::vector<std::vector<int>> scc() { return internal.scc(); }

//  private:
    internal::scc_graph internal;
};

}  // namespace atcoder

#endif  // ATCODER_SCC_HPP

// <<< AtCoder <<<

using namespace std;
using namespace atcoder;
#define PARSE_ARGS(types, ...) if(!PyArg_ParseTuple(args, types, __VA_ARGS__)) return NULL

struct SCCGraph{
    PyObject_HEAD
    scc_graph* graph;
    const int n() const { return graph->internal.num_vertices(); }
};

extern PyTypeObject SCCGraphType;

// >>> SCCGraph definition >>>

static void SCCGraph_dealloc(SCCGraph* self){
    delete self->graph;
    Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject* SCCGraph_new(PyTypeObject* type, PyObject* args, PyObject* kwds){
    return type->tp_alloc(type, 0);
}
static int SCCGraph_init(SCCGraph* self, PyObject* args){
    long n;
    if(!PyArg_ParseTuple(args, "l", &n)) return -1;
    if(n < 0 || n > (long)1e8){
        PyErr_Format(PyExc_IndexError,
            "SCCGraph constructor constraint error (constraint: 0<=n<=1e8, got n=%d)", n);
        return -1;
    }
    self->graph = new scc_graph(n);
    return 0;
}
static PyObject* SCCGraph_add_edge(SCCGraph* self, PyObject* args){
    long from, to;
    PARSE_ARGS("ll", &from, &to);
    if(from < 0 || from >= self->n() || to < 0 || to >= self->n()){
        PyErr_Format(PyExc_IndexError,
            "SCCGraph add_ede index out of range (n=%d, from=%d, to=%d)", self->n(), from, to);
        return (PyObject*)NULL;
    }
    self->graph->add_edge(from, to);
    Py_RETURN_NONE;
}
static PyObject* SCCGraph_scc(SCCGraph* self, PyObject* args){
    const vector<vector<int>>& scc = self->graph->scc();
    PyObject* list = PyList_New(scc.size());
    for(int i = 0; i < scc.size(); i++){
        PyObject* lst = PyList_New(scc[i].size());
        for(int j = 0; j < scc[i].size(); j++){
            PyList_SET_ITEM(lst, j, Py_BuildValue("l", scc[i][j]));
        }
        PyList_SET_ITEM(list, i, lst);
    }
    return list;
}
/*
static PyObject* SCCGraph_repr(PyObject* self){
    PyObject* res = PyUnicode_FromFormat("SCCGraph()");
    return res;
}
*/
static PyMethodDef SCCGraph_methods[] = {
    {"add_edge", (PyCFunction)SCCGraph_add_edge, METH_VARARGS, "Add clause"},
    {"scc", (PyCFunction)SCCGraph_scc, METH_VARARGS, "Check if problem satisfiable"},
    {NULL}  /* Sentinel */
};
PyTypeObject SCCGraphType = {
    PyObject_HEAD_INIT(NULL)
    "acl_scc.SCCGraph",                 /*tp_name*/
    sizeof(SCCGraph),                   /*tp_basicsize*/
    0,                                  /*tp_itemsize*/
    (destructor)SCCGraph_dealloc,       /*tp_dealloc*/
    0,                                  /*tp_print*/
    0,                                  /*tp_getattr*/
    0,                                  /*tp_setattr*/
    0,                                  /*reserved*/
    0,//SCCGraph_repr,                    /*tp_repr*/
    0,                                  /*tp_as_number*/
    0,                                  /*tp_as_sequence*/
    0,                                  /*tp_as_mapping*/
    0,                                  /*tp_hash*/
    0,                                  /*tp_call*/
    0,                                  /*tp_str*/
    0,                                  /*tp_getattro*/
    0,                                  /*tp_setattro*/
    0,                                  /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
    0,                                  /*tp_doc*/
    0,                                  /*tp_traverse*/
    0,                                  /*tp_clear*/
    0,                                  /*tp_richcompare*/
    0,                                  /*tp_weaklistoffset*/
    0,                                  /*tp_iter*/
    0,                                  /*tp_iternext*/
    SCCGraph_methods,                   /*tp_methods*/
    0,                                  /*tp_members*/
    0,                                  /*tp_getset*/
    0,                                  /*tp_base*/
    0,                                  /*tp_dict*/
    0,                                  /*tp_descr_get*/
    0,                                  /*tp_descr_set*/
    0,                                  /*tp_dictoffset*/
    (initproc)SCCGraph_init,            /*tp_init*/
    0,                                  /*tp_alloc*/
    SCCGraph_new,                       /*tp_new*/
    0,                                  /*tp_free*/
    0,                                  /*tp_is_gc*/
    0,                                  /*tp_bases*/
    0,                                  /*tp_mro*/
    0,                                  /*tp_cache*/
    0,                                  /*tp_subclasses*/
    0,                                  /*tp_weaklist*/
    0,                                  /*tp_del*/
    0,                                  /*tp_version_tag*/
    0,                                  /*tp_finalize*/
};

// <<< SCCGraph definition <<<

static PyModuleDef acl_sccmodule = {
    PyModuleDef_HEAD_INIT,
    "acl_scc",
    NULL,
    -1,
};

PyMODINIT_FUNC PyInit_acl_scc(void)
{
    PyObject* m;
    if(PyType_Ready(&SCCGraphType) < 0) return NULL;

    m = PyModule_Create(&acl_sccmodule);
    if(m == NULL) return NULL;

    Py_INCREF(&SCCGraphType);
    if (PyModule_AddObject(m, "SCCGraph", (PyObject*)&SCCGraphType) < 0) {
        Py_DECREF(&SCCGraphType);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}
"""
code_scc_graph_setup = r"""
from distutils.core import setup, Extension
module = Extension(
    "acl_scc",
    sources=["scc_graph.cpp"],
    extra_compile_args=["-O3", "-march=native", "-std=c++14"]
)
setup(
    name="acl_scc",
    version="0.0.1",
    description="wrapper for atcoder library scc",
    ext_modules=[module]
)
"""

import os
import sys

if sys.argv[-1] == "ONLINE_JUDGE" or os.getcwd() != "/imojudge/sandbox":
    with open("scc_graph.cpp", "w") as f:
        f.write(code_scc_graph)
    with open("scc_graph_setup.py", "w") as f:
        f.write(code_scc_graph_setup)
    os.system(f"{sys.executable} scc_graph_setup.py build_ext --inplace")

from acl_scc import SCCGraph

def main():
    N, M = map(int, sys.stdin.buffer.readline().split())
    m = map(int, sys.stdin.buffer.read().split())
    g = SCCGraph(N)
    for a, b in zip(m, m):
        g.add_edge(a, b)
    scc = g.scc()
    print(len(scc))
    for v in scc:
        print(len(v), " ".join(map(str, v)))

main()

import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)

class SCC:

    def __init__(self, n):
        self.n = n
        self.graph = [[] for i in range(n)]
        self.graph_rev = [[] for i in range(n)]
        self.used = [False]*n

    def add_edge(self, fr, to):
        if fr == to:
            return
        self.graph[fr].append(to)
        self.graph_rev[to].append(fr)

    def dfs(self, node, graph):
        self.used[node] = True
        for nex in graph[node]:
            if self.used[nex]:
                continue
            self.dfs(nex,graph)
        self.order.append(node)

    def first_dfs(self):
        self.used = [False]*self.n
        self.order = []
        for i in range(self.n):
            if self.used[i]:
                continue
            self.dfs(i,self.graph)

    def second_dfs(self):
        self.used = [False]*self.n
        self.ans = []
        for node in reversed(self.order):
            if self.used[node]:
                continue
            self.used[node] = True
            self.order = []
            self.dfs(node, self.graph_rev)
            #self.order.reverse()
            self.ans.append(self.order)

    def scc(self):
        self.first_dfs()
        self.second_dfs()
        return self.ans

def main():
    n,m = map(int,input().split())
    scc = SCC(n)
    for _ in range(m):
        a,b = map(int,input().split())
        scc.add_edge(a,b)

    ans = scc.scc()

    print(len(ans))
    for i in ans:
        print(len(i),*i)

if __name__ == "__main__":
    main()

Score : <var>100</var> points

Problem Statement

You are given a directed graph with <var>N</var> vertices and <var>M</var> edges, not necessarily simple. The <var>i</var>-th edge is oriented from the vertex <var>a_i</var> to the vertex <var>b_i</var>.
Divide this graph into strongly connected components and print them in their topological order.

Constraints

<var>1 \leq N \leq 500,000</var>

<var>1 \leq M \leq 500,000</var>

<var>0 \leq a_i, b_i < N</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>a_0</var> <var>b_0</var>
<var>a_1</var> <var>b_1</var>
:
<var>a_{M - 1}</var> <var>b_{M - 1}</var>

Output

Print <var>1+K</var> lines, where <var>K</var> is the number of strongly connected components.
Print <var>K</var> on the first line.
Print the information of each strongly connected component in next <var>K</var> lines in the following format, where <var>l</var> is the number of vertices in the strongly connected component and <var>v_i</var> is the index of the vertex in it.

<var>l</var> <var>v_0</var> <var>v_1</var> ... <var>v_{l-1}</var>

Here, for each edge <var>(a_i, b_i)</var>, <var>b_i</var> should not appear in earlier line than <var>a_i</var>.

If there are multiple correct output, print any of them.

Sample Input 1

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

Sample Output 1

4
1 5
2 4 1
1 2
2 3 0


import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8, i8[:, :], i8[:], i8[:], i8[:], i8[:], i8[:], i8, i8, i8, i8),
      cache=True)
def scc_dfs(N, G, idx, low, ord, ids, visited, now_ord, group_num, vis_i, v):
    low[v] = ord[v] = now_ord
    now_ord += 1
    visited[vis_i], vis_i = v, vis_i + 1
    for e in range(idx[v], idx[v + 1]):
        to = G[e, 1]
        if ord[to] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, to)
            low[v] = min(low[v], low[to])
        else:
            low[v] = min(low[v], ord[to])
    if low[v] == ord[v]:
        while True:
            u, vis_i = visited[vis_i - 1], vis_i - 1
            ord[u] = N
            ids[u] = group_num
            if u == v:
                break
        group_num += 1
    return now_ord, group_num, vis_i

@njit((i8, i8[:, :]), cache=True)
def scc(N, G):
    idx = np.searchsorted(G[:, 0], np.arange(N + 1))
    low = np.zeros(N, np.int64)
    ord = np.zeros(N, np.int64) - 1
    now_ord = 0
    group_num = 0
    visited, vis_i = np.empty(N, np.int64), 0
    ids = np.zeros(N, np.int64)
    for v in range(N):
        if ord[v] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, v)
    return group_num, group_num - ids - 1

@njit((i8, i8[:, :]), cache=True)
def main(N, G):
    n_comp, comp = scc(N, G)

N, M = map(int, readline().split())
AB = np.array(read().split(), np.int64).reshape(-1, 2)

AB = AB[np.argsort(AB[:, 0])]

main(N, AB)


# TODO: メモリリーク確認
# TODO: __repr__ を書く

code_two_sat = r"""
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

// 元のライブラリの private を剥がした

// >>> AtCoder >>>

#ifndef ATCODER_TWOSAT_HPP
#define ATCODER_TWOSAT_HPP 1

#ifndef ATCODER_INTERNAL_SCC_HPP
#define ATCODER_INTERNAL_SCC_HPP 1

#include <algorithm>
#include <utility>
#include <vector>

namespace atcoder {
namespace internal {

template <class E> struct csr {
    std::vector<int> start;
    std::vector<E> elist;
    csr(int n, const std::vector<std::pair<int, E>>& edges)
        : start(n + 1), elist(edges.size()) {
        for (auto e : edges) {
            start[e.first + 1]++;
        }
        for (int i = 1; i <= n; i++) {
            start[i] += start[i - 1];
        }
        auto counter = start;
        for (auto e : edges) {
            elist[counter[e.first]++] = e.second;
        }
    }
};

// Reference:
// R. Tarjan,
// Depth-First Search and Linear Graph Algorithms
struct scc_graph {
  public:
    scc_graph(int n) : _n(n) {}

    int num_vertices() { return _n; }

    void add_edge(int from, int to) { edges.push_back({from, {to}}); }

    // @return pair of (# of scc, scc id)
    std::pair<int, std::vector<int>> scc_ids() {
        auto g = csr<edge>(_n, edges);
        int now_ord = 0, group_num = 0;
        std::vector<int> visited, low(_n), ord(_n, -1), ids(_n);
        visited.reserve(_n);
        auto dfs = [&](auto self, int v) -> void {
            low[v] = ord[v] = now_ord++;
            visited.push_back(v);
            for (int i = g.start[v]; i < g.start[v + 1]; i++) {
                auto to = g.elist[i].to;
                if (ord[to] == -1) {
                    self(self, to);
                    low[v] = std::min(low[v], low[to]);
                } else {
                    low[v] = std::min(low[v], ord[to]);
                }
            }
            if (low[v] == ord[v]) {
                while (true) {
                    int u = visited.back();
                    visited.pop_back();
                    ord[u] = _n;
                    ids[u] = group_num;
                    if (u == v) break;
                }
                group_num++;
            }
        };
        for (int i = 0; i < _n; i++) {
            if (ord[i] == -1) dfs(dfs, i);
        }
        for (auto& x : ids) {
            x = group_num - 1 - x;
        }
        return {group_num, ids};
    }

    std::vector<std::vector<int>> scc() {
        auto ids = scc_ids();
        int group_num = ids.first;
        std::vector<int> counts(group_num);
        for (auto x : ids.second) counts[x]++;
        std::vector<std::vector<int>> groups(ids.first);
        for (int i = 0; i < group_num; i++) {
            groups[i].reserve(counts[i]);
        }
        for (int i = 0; i < _n; i++) {
            groups[ids.second[i]].push_back(i);
        }
        return groups;
    }

  private:
    int _n;
    struct edge {
        int to;
    };
    std::vector<std::pair<int, edge>> edges;
};

}  // namespace internal

}  // namespace atcoder

#endif  // ATCODER_INTERNAL_SCC_HPP

#include <cassert>
#include <vector>

namespace atcoder {

// Reference:
// B. Aspvall, M. Plass, and R. Tarjan,
// A Linear-Time Algorithm for Testing the Truth of Certain Quantified Boolean
// Formulas
struct two_sat {
  public:
    two_sat() : _n(0), scc(0) {}
    two_sat(int n) : _n(n), _answer(n), scc(2 * n) {}

    void add_clause(int i, bool f, int j, bool g) {
        assert(0 <= i && i < _n);
        assert(0 <= j && j < _n);
        scc.add_edge(2 * i + (f ? 0 : 1), 2 * j + (g ? 1 : 0));
        scc.add_edge(2 * j + (g ? 0 : 1), 2 * i + (f ? 1 : 0));
    }
    bool satisfiable() {
        auto id = scc.scc_ids().second;
        for (int i = 0; i < _n; i++) {
            if (id[2 * i] == id[2 * i + 1]) return false;
            _answer[i] = id[2 * i] < id[2 * i + 1];
        }
        return true;
    }
    std::vector<bool> answer() { return _answer; }

//  private:
    int _n;
    std::vector<bool> _answer;
    internal::scc_graph scc;
};

}  // namespace atcoder

#endif  // ATCODER_TWOSAT_HPP

// <<< AtCoder <<<

using namespace std;
using namespace atcoder;
#define PARSE_ARGS(types, ...) if(!PyArg_ParseTuple(args, types, __VA_ARGS__)) return NULL

struct TwoSAT{
    PyObject_HEAD
    two_sat* ts;
};

extern PyTypeObject TwoSATType;

// >>> TwoSAT definition >>>

static void TwoSAT_dealloc(TwoSAT* self){
    delete self->ts;
    Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject* TwoSAT_new(PyTypeObject* type, PyObject* args, PyObject* kwds){
    return type->tp_alloc(type, 0);
}
static int TwoSAT_init(TwoSAT* self, PyObject* args){
    long n;
    if(!PyArg_ParseTuple(args, "l", &n)) return -1;
    if(n < 0 || n > (long)1e8){
        PyErr_Format(PyExc_IndexError,
            "TwoSAT constructor constraint error (constraint: 0<=n<=1e8, got n=%d)", n);
        return -1;
    }
    self->ts = new two_sat(n);
    return 0;
}
static PyObject* TwoSAT_add_clause(TwoSAT* self, PyObject* args){
    long i, j;
    int f, g;
    PARSE_ARGS("lplp", &i, &f, &j, &g);
    if(i < 0 || i >= self->ts->_n || j < 0 || j >= self->ts->_n){
        PyErr_Format(PyExc_IndexError,
            "TwoSAT add_clause index out of range (n=%d, i=%d, j=%d)", self->ts->_n, i, j);
        return (PyObject*)NULL;
    }
    self->ts->add_clause(i, (bool)f, j, (bool)g);
    Py_RETURN_NONE;
}
static PyObject* TwoSAT_satisfiable(TwoSAT* self, PyObject* args){
    PyObject* res = self->ts->satisfiable() ? Py_True : Py_False;
    return Py_BuildValue("O", res);
}
static PyObject* TwoSAT_answer(TwoSAT* self, PyObject* args){
    const vector<bool>& answer = self->ts->answer();
    const int& n = self->ts->_n;
    PyObject* list = PyList_New(n);
    for(int i = 0; i < n; i++){
        PyList_SET_ITEM(list, i, Py_BuildValue("O", answer[i] ? Py_True : Py_False));
    }
    return list;
}
/*
static PyObject* TwoSAT_repr(PyObject* self){
    PyObject* res = PyUnicode_FromFormat("TwoSAT()");
    return res;
}
*/
static PyMethodDef TwoSAT_methods[] = {
    {"add_clause", (PyCFunction)TwoSAT_add_clause, METH_VARARGS, "Add clause"},
    {"satisfiable", (PyCFunction)TwoSAT_satisfiable, METH_VARARGS, "Check if problem satisfiable"},
    {"answer", (PyCFunction)TwoSAT_answer, METH_VARARGS, "Get answer"},
    {NULL}  /* Sentinel */
};
PyTypeObject TwoSATType = {
    PyObject_HEAD_INIT(NULL)
    "acl_twosat.TwoSAT",                   /*tp_name*/
    sizeof(TwoSAT),                     /*tp_basicsize*/
    0,                                  /*tp_itemsize*/
    (destructor)TwoSAT_dealloc,         /*tp_dealloc*/
    0,                                  /*tp_print*/
    0,                                  /*tp_getattr*/
    0,                                  /*tp_setattr*/
    0,                                  /*reserved*/
    0,//TwoSAT_repr,                      /*tp_repr*/
    0,                                  /*tp_as_number*/
    0,                                  /*tp_as_sequence*/
    0,                                  /*tp_as_mapping*/
    0,                                  /*tp_hash*/
    0,                                  /*tp_call*/
    0,                                  /*tp_str*/
    0,                                  /*tp_getattro*/
    0,                                  /*tp_setattro*/
    0,                                  /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
    0,                                  /*tp_doc*/
    0,                                  /*tp_traverse*/
    0,                                  /*tp_clear*/
    0,                                  /*tp_richcompare*/
    0,                                  /*tp_weaklistoffset*/
    0,                                  /*tp_iter*/
    0,                                  /*tp_iternext*/
    TwoSAT_methods,                     /*tp_methods*/
    0,                                  /*tp_members*/
    0,                                  /*tp_getset*/
    0,                                  /*tp_base*/
    0,                                  /*tp_dict*/
    0,                                  /*tp_descr_get*/
    0,                                  /*tp_descr_set*/
    0,                                  /*tp_dictoffset*/
    (initproc)TwoSAT_init,              /*tp_init*/
    0,                                  /*tp_alloc*/
    TwoSAT_new,                         /*tp_new*/
    0,                                  /*tp_free*/
    0,                                  /*tp_is_gc*/
    0,                                  /*tp_bases*/
    0,                                  /*tp_mro*/
    0,                                  /*tp_cache*/
    0,                                  /*tp_subclasses*/
    0,                                  /*tp_weaklist*/
    0,                                  /*tp_del*/
    0,                                  /*tp_version_tag*/
    0,                                  /*tp_finalize*/
};

// <<< TwoSAT definition <<<

static PyModuleDef acl_twosatmodule = {
    PyModuleDef_HEAD_INIT,
    "acl_twosat",
    NULL,
    -1,
};

PyMODINIT_FUNC PyInit_acl_twosat(void)
{
    PyObject* m;
    if(PyType_Ready(&TwoSATType) < 0) return NULL;

    m = PyModule_Create(&acl_twosatmodule);
    if(m == NULL) return NULL;

    Py_INCREF(&TwoSATType);
    if (PyModule_AddObject(m, "TwoSAT", (PyObject*)&TwoSATType) < 0) {
        Py_DECREF(&TwoSATType);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}
"""
code_two_sat_setup = r"""
from distutils.core import setup, Extension
module = Extension(
    "acl_twosat",
    sources=["two_sat.cpp"],
    extra_compile_args=["-O3", "-march=native", "-std=c++14"]
)
setup(
    name="acl_twosat",
    version="0.0.1",
    description="wrapper for atcoder library twosat",
    ext_modules=[module]
)
"""

import os
import sys

if sys.argv[-1] == "ONLINE_JUDGE" or os.getcwd() != "/imojudge/sandbox":
    with open("two_sat.cpp", "w") as f:
        f.write(code_two_sat)
    with open("two_sat_setup.py", "w") as f:
        f.write(code_two_sat_setup)
    os.system(f"{sys.executable} two_sat_setup.py build_ext --inplace")

from acl_twosat import TwoSAT

def main():
    N, D = map(int, input().split())
    XY = [list(map(int, input().split())) for _ in range(N)]
    ts = TwoSAT(N)
    for i, (xi, yi) in enumerate(XY):
        for j, (xj, yj) in enumerate(XY[i+1:], i+1):
            if abs(xi-xj) < D:
                ts.add_clause(i, False, j, False)
            if abs(xi-yj) < D:
                ts.add_clause(i, False, j, True)
            if abs(yi-xj) < D:
                ts.add_clause(i, True, j, False)
            if abs(yi-yj) < D:
                ts.add_clause(i, True, j, True)
    if not ts.satisfiable():
        print("No")
        return
    print("Yes")
    answer = ts.answer()
    for a, (x, y) in zip(answer, XY):
        print(x if a else y)

main()

N,D=map(int,input().split())
F=[tuple(map(int,input().split())) for i in range(N)]

EDGE=[[] for i in range(2*N)]
EDGE_INV=[[] for i in range(2*N)]

# 0～N : X_i
# N+1～2N: Y_i = ￢X_i

for i in range(N):
    x1,y1=F[i]

    for j in range(i,N):
        x2,y2=F[j]

        if abs(x1-x2)<D and i!=j:
            EDGE[i].append(N+j)
            EDGE[j].append(N+i)

            EDGE_INV[N+j].append(i)
            EDGE_INV[N+i].append(j)

        if abs(x1-y2)<D:
            EDGE[i].append(j)
            EDGE[N+j].append(N+i)

            EDGE_INV[j].append(i)
            EDGE_INV[N+i].append(N+j)

        if abs(y1-x2)<D:
            EDGE[N+i].append(N+j)
            EDGE[j].append(i)

            EDGE_INV[N+j].append(N+i)
            EDGE_INV[i].append(j)

        if abs(y1-y2)<D and i!=j:
            EDGE[N+i].append(j)
            EDGE[N+j].append(i)

            EDGE_INV[j].append(N+i)
            EDGE_INV[i].append(N+j)

QUE = list(range(2*N))
check=[0]*(2*N)
TOP_SORT=[]

def dfs(x):
    if check[x]==1:
        return
    check[x]=1

    for to in EDGE[x]:
        if check[to]==0:
            dfs(to)

    TOP_SORT.append(x) # 全ての点からDFSを行い, 帰りがけに点を答えに入れる
    check[x]=1

while QUE:
    x=QUE.pop()
    dfs(x)

USE=[0]*(2*N)
SCC=[]

def dfs2(x):
    Q=[x]
    USE[x]=1
    ANS=[]

    while Q:
        x=Q.pop()
        ANS.append(x)
        for to in EDGE_INV[x]:
            if USE[to]==0:
                USE[to]=1
                Q.append(to)
    return ANS

for x in TOP_SORT[::-1]:
    if USE[x]==0:
        SCC.append(dfs2(x))

PLACE=[-1]*(2*N)
for i in range(len(SCC)):
    for x in SCC[i]:
        PLACE[x]=i

ANS=[-1]*N
flag=1
for i in range(N):
    if PLACE[i]==PLACE[N+i]:
        flag=0
        break

    elif PLACE[i]>PLACE[N+i]:
        ANS[i]=F[i][0]
    else:
        ANS[i]=F[i][1]

if flag==0:
    print("No")
else:
    print("Yes")
    for ans in ANS:
        print(ans)

Score : <var>100</var> points

Problem Statement

Consider placing <var>N</var> flags on a line. Flags are numbered through <var>1</var> to <var>N</var>.

Flag <var>i</var> can be placed on the coordinate <var>X_i</var> or <var>Y_i</var>.
For any two different flags, the distance between them should be at least <var>D</var>.

Decide whether it is possible to place all <var>N</var> flags. If it is possible, print such a configulation.

Constraints

<var>1 \leq N \leq 1000</var>

<var>0 \leq D \leq 10^9</var>

<var>0 \leq X_i < Y_i \leq 10^9</var>

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>D</var>
<var>X_1</var> <var>Y_1</var>
<var>X_2</var> <var>Y_2</var>
<var>\vdots</var>
<var>X_N</var> <var>Y_N</var>

Output

Print No if it is impossible to place <var>N</var> flags.

If it is possible, print Yes first.
After that, print <var>N</var> lines. <var>i</var>-th line of them should contain the coodinate of flag <var>i</var>.

Sample Input 1

3 2
1 4
2 5
0 6

Sample Output 1

Yes
4
2
0

Sample Input 2

3 3
1 4
2 5
0 6

Sample Output 2

No


header_code = """

#include "/opt/atcoder-stl/atcoder/internal_bit.hpp"
#include "/opt/atcoder-stl/atcoder/lazysegtree.hpp"
#include "/opt/atcoder-stl/atcoder/modint.hpp"
#include <vector>
#include <algorithm>
#include <cassert>

namespace aclython {

template <class S, S (*op)(S, S), S (*e)()> struct segtree {
  public:
    segtree() : segtree(0) {}
    segtree(int n) : segtree(std::vector<S>(n, e())) {}
    segtree(const std::vector<S>& v) : _n(int(v.size())) {
        log = atcoder::internal::ceil_pow2(_n);
        size = 1 << log;
        d = std::vector<S>(2 * size, e());
        for (int i = 0; i < _n; i++) d[size + i] = v[i];
        for (int i = size - 1; i >= 1; i--) {
            update(i);
        }
    }

    void set(int p, S x) {
        assert(0 <= p && p < _n);
        p += size;
        d[p] = x;
        for (int i = 1; i <= log; i++) update(p >> i);
    }

    S get(int p) {
        assert(0 <= p && p < _n);
        return d[p + size];
    }

    S prod(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        S sml = e(), smr = e();
        l += size;
        r += size;

        while (l < r) {
            if (l & 1) sml = op(sml, d[l++]);
            if (r & 1) smr = op(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }
        return op(sml, smr);
    }

    S all_prod() { return d[1]; }

    template <bool (*f)(S)> int max_right(int l, S b) {
        return max_right(l, b, [](S x, S y) { return f(x, y); });
    }
    template <class F> int max_right(int l, S b, F f) {
        assert(0 <= l && l <= _n);
        assert(f(e()));
        if (l == _n) return _n;
        l += size;
        S sm = e();
        do {
            while (l % 2 == 0) l >>= 1;
            if (!f(op(sm, d[l]), b)) {
                while (l < size) {
                    l = (2 * l);
                    if (f(op(sm, d[l]), b)) {
                        sm = op(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = op(sm, d[l]);
            l++;
        } while ((l & -l) != l);
        return _n;
    }

    template <bool (*f)(S)> int min_left(int r, S b) {
        return min_left(r, b, [](S x, S y) { return f(x, y); });
    }
    template <class F> int min_left(int r, S b, F f) {
        assert(0 <= r && r <= _n);
        assert(f(e()));
        if (r == 0) return 0;
        r += size;
        S sm = e();
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!f(op(d[r], sm), b)) {
                while (r < size) {
                    r = (2 * r + 1);
                    if (f(op(d[r], sm), b)) {
                        sm = op(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = op(d[r], sm);
        } while ((r & -r) != r);
        return 0;
    }

  private:
    int _n, size, log;
    std::vector<S> d;

    void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
};

int min_op(int n, int m){
    return std::min(n, m);
}

int min_e(){
    return (int)1e9;
}

struct segtree_min {
    public:
        segtree_min() : segtree_min(0) {}
        segtree_min(int n) : segtree_min(std::vector<int>(n, min_e())) {}
        segtree_min(const std::vector<int>& vec) : seg(vec) {}

        void set(int p, int x) {seg.set(p, x);}
        int get(int p) {return seg.get(p);}
        int prod(int l, int r) {return seg.prod(l, r);}
        int all_prod() {return seg.all_prod();}

        int max_right(int l, int v) {return seg.max_right(l, v, [](int x, int y) { return x<y; });}
        int min_left(int r, int v) {return seg.min_left(r, v, [](int x, int y) { return x<y; });}

    private:
        segtree<int, min_op, min_e> seg;
};

int max_op(int n, int m){
    return std::max(n, m);
}

int max_e(){
    return 0;
}

struct segtree_max {
    public:
        segtree_max() : segtree_max(0) {}
        segtree_max(int n) : segtree_max(std::vector<int>(n, max_e())) {}
        segtree_max(const std::vector<int>& vec) : seg(vec) {}

        void set(int p, int x) {seg.set(p, x);}
        int get(int p) {return seg.get(p);}
        int prod(int l, int r) {return seg.prod(l, r);}
        int all_prod() {return seg.all_prod();}

        int max_right(int l, int v) {return seg.max_right(l, v, [](int x, int y) { return x<y; });}
        int min_left(int r, int v) {return seg.min_left(r, v, [](int x, int y) { return x<y; });}

    private:
        segtree<int, max_op, max_e> seg;
};

using mint = atcoder::modint998244353;

struct S {
    mint a;
    int size;
    S(mint _a, int _size) : a(_a) ,size(_size) {}
    S(int _a, int _size) : a(_a) ,size(_size) {}
    S(const S &s) : a(s.a), size(s.size) {}
    int get_a() { return (int)a.val(); }
};

struct F {
    mint a, b;
    F(mint _a, mint _b) : a(_a), b(_b) {}
    F(int _a, int _b) : a(_a), b(_b) {}
    F(const F &f) : a(f.a), b(f.b) {}
    int get_a() { return (int)a.val(); }
    int get_b() { return (int)b.val(); }
};

S op(S l, S r) { return S{l.a + r.a, l.size + r.size}; }

S e() { return S{0, 0}; }

S mapping(F l, S r) { return S{r.a * l.a + r.size * l.b, r.size}; }

F composition(F l, F r) { return F{r.a * l.a, r.b * l.a + l.b}; }

F id() { return F{1, 0}; }

struct lazy_segtree{
    lazy_segtree() : lazy_segtree(0) {}
    lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}
    lazy_segtree(const std::vector<S>& vec) : seg(vec) {}
    void set(int p, S x) { seg.set(p, x); }
    S get(int p) { return seg.get(p); }
    S prod(int l, int r) { return seg.prod(l, r); }
    S all_prod() { return seg.all_prod(); }
    void apply(int p, F f) { seg.apply(p, f); }
    void apply(int l, int r, F f) { seg.apply(l, r, f); }
    private:
        atcoder::lazy_segtree<S, op, e, F, mapping, composition, id> seg;
};

}
"""

code = """

# distutils: language=c++
# distutils: include_dirs=[/home/USERNAME/.local/lib/python3.8/site-packages/numpy/core/include, /opt/atcoder-stl]
# cython: boundscheck=False
# cython: wraparound=False

from libc.stdio cimport getchar, printf
from libcpp.vector cimport vector
from libcpp cimport bool
from libcpp.string cimport string
cdef extern from "<atcoder/twosat>" namespace "atcoder":
    cdef cppclass two_sat:
        two_sat(int n)
        void add_clause(int i, bool f, int j, bool g)
        bool satisfiable()
        vector[bool] answer()

cdef class TwoSat:
    cdef two_sat *_thisptr
    def __cinit__(self, int n):
        self._thisptr = new two_sat(n)
    cpdef void add_clause(self, int i, bool f, int j, bool g):
        self._thisptr.add_clause(i, f, j, g)
    cpdef bool satisfiable(self):
        return self._thisptr.satisfiable()
    cpdef vector[bool] answer(self):
        return self._thisptr.answer()
cpdef inline vector[int] ReadInt(int n):
    cdef int b, c
    cdef vector[int] *v = new vector[int]()
    for i in range(n):
        c = 0
        while 1:
            b = getchar() - 48
            if b < 0: break
            c = c * 10 + b
        v.push_back(c)
    return v[0]

cpdef inline vector[string] Read(int n):
    cdef char c
    cdef vector[string] *vs = new vector[string]()
    cdef string *s
    for i in range(n):
        s = new string()
        while 1:
            c = getchar()
            if c<=32: break
            s.push_back(c)
        vs.push_back(s[0])
    return vs[0]

cpdef inline void PrintLongN(vector[long] l, int n):
    for i in range(n): printf("%ld\\n", l[i])

cpdef inline void PrintLong(vector[long] l, int n):
    for i in range(n): printf("%ld ", l[i])
"""

import os, sys, getpass

if sys.argv[-1] == 'ONLINE_JUDGE':
    code = code.replace("USERNAME", getpass.getuser())
    open('intermediate.hpp','w').write(header_code)
    open('atcoder.pyx','w').write(code)
    os.system('cythonize -i -3 -b atcoder.pyx')
    sys.exit(0)

from atcoder import ReadInt, TwoSat, PrintLongN

def main():
  N,D=ReadInt(2)
  xy = ReadInt(2*N)
  ts=TwoSat(N)
  for i in range(N-1):
    for j in range(i+1,N):
      for k1,k2 in [(0,0),(0,1),(1,0),(1,1)]:
        pos1,pos2 = xy[2*i+k1],xy[2*j+k2]
        if abs(pos2-pos1)<D:
          ts.add_clause(i,k1^1,j,k2^1)

  if ts.satisfiable():
    print('Yes')
    ans = ts.answer()
    ans = [xy[2*i+ans[i]] for i in range(N)]
    PrintLongN(ans, len(ans))
  else:
    print('No')

if __name__=="__main__":
  main()


import numpy as np
i4 = np.int32
i8 = np.int64

def solve(a, b, H, W):
    ret = np.empty(H, i8)
    for i in range(H):
        ret[i] = -1
    dp0 = np.arange(W)
    dp = np.arange(W)
    arg0 = W - 1
    arg = 0
    for i in range(H):
        r1 = np.searchsorted(dp, a[i])
        r2 = np.searchsorted(dp, b[i])
        if b[i] == W:
            if r1 == 0:
                return ret
            else:
                dp0 = dp0[: r1]
                dp = dp[: r1]
        else:
            dp[r1:r2] = b[i]

        if arg0 > -1:
            if r1 <= arg0 < r2:
                for j in range(r1 - 1, -1, -1):
                    if dp[j] == dp0[j]:
                        arg0 = j
                        ret[i] = i + 1
                        break
                else:
                    arg0 = -1
                    arg = np.argmin(dp - dp0)
                    ret[i] = dp[arg] - dp0[arg] + i + 1
            else:
                ret[i] = i + 1
        else:
            if r1 <= arg < r2:
                arg = np.argmin(dp - dp0)
            ret[i] = dp[arg] - dp0[arg] + i + 1

        if i % 1000 == 999:
            m = 0
            prev = dp[0]
            for k in range(1, dp.shape[0]):
                if dp[k] > prev:
                    dp0[m] = dp0[k - 1]
                    dp[m] = prev
                    m += 1
                    prev = dp[k]
            else:
                dp0[m] = dp0[dp0.shape[0] - 1]
                dp[m] = prev
                m += 1
            dp0 = dp0[: m]
            dp = dp[: m]
            if arg0 > -1:
                for j in range(m - 1, -1, -1):
                    if dp[j] == dp0[j]:
                        arg0 = j
                        break
            else:
                arg = np.argmin(dp - dp0)
    return ret

def main(in_file):
    stdin = open(in_file)
    H, W = [int(x) for x in stdin.readline().split()]
    ab = np.fromstring(stdin.read(), i8, sep=' ').reshape((-1, 2)).T.copy()
    ans = solve(ab[0] - 1, ab[1], H, W)
    p = '\n'.join([str(x) for x in ans.tolist()])
    print(p)

def cc_export():
    from numba.pycc import CC
    from numba.types import Array, int64
    cc = CC('my_module')
    cc.export('solve', (Array(int64, 1, 'C'), Array(int64, 1, 'C'), int64, int64))(solve)
    cc.compile()

if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    from my_module import solve
    main('/dev/stdin')

# 写経
# https://atcoder.jp/contests/abc177/submissions/16463802

import numpy as np
i4 = np.int32
i8 = np.int64

def solve(a, b, H, W):
    ret = np.empty(H, i8)
    for i in range(H):
        ret[i] = -1
    dp0 = np.arange(W) #初期位置
    dp = np.arange(W) #現在位置
    arg0 = W - 1
    arg = 0
    for i in range(H):
        r1 = np.searchsorted(dp, a[i])
        r2 = np.searchsorted(dp, b[i])
        if b[i] == W: #右端まで壁が続く場合
            if r1 == 0:
                return ret
            else:
                dp0 = dp0[: r1] #壁があるところより先は無視する
                dp = dp[: r1]
        else:
            dp[r1:r2] = b[i] #合流させる

        if arg0 > -1:   #直進する流れが残っている場合
            if r1 <= arg0 < r2: #壁がある場合
                for j in range(r1 - 1, -1, -1):
                    if dp[j] == dp0[j]:
                        arg0 = j    #ここまで直進してきた他の流れに乗り換える
                        ret[i] = i + 1
                        break
                else:
                    arg0 = -1
                    arg = np.argmin(dp - dp0) #残っている値の中での最小値
                    ret[i] = dp[arg] - dp0[arg] + i + 1
            else:
                ret[i] = i + 1
        else:
            if r1 <= arg < r2:
                arg = np.argmin(dp - dp0)
            ret[i] = dp[arg] - dp0[arg] + i + 1

        if i % 1000 == 999:
            m = 0
            prev = dp[0]
            for k in range(1, dp.shape[0]):
                if dp[k] > prev: #dp[0]とは別の流れにあるものについて
                    dp0[m] = dp0[k - 1] #最小のずれを持つもののみ残してまとめる
                    dp[m] = prev
                    m += 1
                    prev = dp[k]
            else: #流れが一つのみの場合はこの流れの実を追いかける
                dp0[m] = dp0[dp0.shape[0] - 1]
                dp[m] = prev
                m += 1
            dp0 = dp0[: m]
            dp = dp[: m]
            if arg0 > -1: #現在最小である流れなどの情報も更新しておく
                for j in range(m - 1, -1, -1):
                    if dp[j] == dp0[j]:
                        arg0 = j
                        break
            else:
                arg = np.argmin(dp - dp0)

    return ret

def main(in_file):
    stdin = open(in_file)
    H, W = [int(x) for x in stdin.readline().split()]
    ab = np.fromstring(stdin.read(), i8, sep=' ').reshape((-1, 2)).T.copy()
    ans = solve(ab[0] - 1, ab[1], H, W)
    p = '\n'.join([str(x) for x in ans.tolist()])
    print(p)

def cc_export():
    from numba.pycc import CC
    from numba.types import Array, int64
    cc = CC('my_module')
    cc.export('solve', (Array(int64, 1, 'C'), Array(int64, 1, 'C'), int64, int64))(solve)
    cc.compile()

if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    from my_module import solve
    main('/dev/stdin')

Score : <var>600</var> points

Problem Statement

There is a grid of squares with <var>H+1</var> horizontal rows and <var>W</var> 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 <var>i</var> from <var>1</var> through <var>H</var>, you cannot move down from the <var>A_i</var>-th, <var>(A_i + 1)</var>-th, <var>\ldots</var>, <var>B_i</var>-th squares from the left in the <var>i</var>-th row from the top.

For each integer <var>k</var> from <var>1</var> through <var>H</var>, find the minimum number of moves needed to reach one of the squares in the <var>(k+1)</var>-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 <var>(k+1)</var>-th row can be reached, print -1 instead.

Constraints

<var>1 \leq H,W \leq 2\times 10^5</var>

<var>1 \leq A_i \leq B_i \leq W</var>

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>A_1</var> <var>B_1</var>
<var>A_2</var> <var>B_2</var>
<var>:</var>
<var>A_H</var> <var>B_H</var>

Output

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

Sample Input 1

4 4
2 4
1 1
2 3
2 4

Sample Output 1

1
3
6
-1

Let <var>(i,j)</var> denote the square at the <var>i</var>-th row from the top and <var>j</var>-th column from the left.

For <var>k=1</var>, we need one move such as <var>(1,1)</var> → <var>(2,1)</var>.

For <var>k=2</var>, we need three moves such as <var>(1,1)</var> → <var>(2,1)</var> → <var>(2,2)</var> → <var>(3,2)</var>.

For <var>k=3</var>, we need six moves such as <var>(1,1)</var> → <var>(2,1)</var> → <var>(2,2)</var> → <var>(3,2)</var> → <var>(3,3)</var> → <var>(3,4)</var> → <var>(4,4)</var>.

For <var>k=4</var>, it is impossible to reach any square in the fifth row from the top.


def prog(x):
    n = len(x)

    def count25(s): # count25(0)
        if s.find('.') == -1:
            s += '.'
        s = s.rstrip('0')
        decimal_point = s.find('.')
        int_part = s[:decimal_point]
        float_part = s[decimal_point+1:]
        float_part += '0' * (9 - len(float_part))
        n = int(int_part + float_part)
        if n == 0:
            return (0, 0)
        two = five = 0
        while n % 2 == 0:
            two += 1
            n //= 2
        while n % 5 == 0:
            five += 1
            n //= 5
        return (two, five)

    d = {}
    for a in x:
        t = count25(a)
        d.setdefault(t, 0)
        d[t] += 1
    two_five = list(d.keys())
    count = 0
    for i in range(len(two_five)): # i = 0
        two, five = two_five[i]
        cnt = d[two_five[i]]
        if two >= 9 and five >= 9:
            count += cnt * (cnt -1) // 2
        for j in range(i + 1, len(two_five)):
            two2, five2 = two_five[j]
            if two + two2 >= 18 and five + five2 >= 18:
                count += cnt * d[two_five[j]]
    print(count)

n = int(input())
x = [input() for i in range(n)]
prog(x)

def conv(s):
    if s.find('.') == -1:
        s += '.'
    s = s.rstrip('0')
    t = len(s) - s.find('.') - 1
    a = int(s.replace('.', ''))
    if a == 0:
        return (0, 0)
    x, y = -t, -t
    while a % 5 == 0:
        x += 1
        a //= 5
    while a % 2 == 0:
        y += 1
        a //= 2
    return (x, y)

N, *A = open(0).read().split()
N = int(N)

d = {}
for a in A:
    t = conv(a)
    d.setdefault(t, 0)
    d[t] += 1

result = 0
xs = list(d.keys())
for i in range(len(xs)):
    x, y = xs[i]
    t = d[xs[i]]
    if x >= 0 and y >= 0:
        result += t * (t - 1) // 2
    for j in range(i + 1, len(xs)):
        m, n = xs[j]
        if x + m >= 0 and y + n >= 0:
            result += t * d[xs[j]]
print(result)

Score : <var>300</var> points

Problem Statement

You are given <var>N</var> real values <var>A_1, A_2, \ldots, A_N</var>.
Compute the number of pairs of indices <var>(i, j)</var>
    such that <var>i < j</var> and the product <var>A_i \cdot A_j</var> is integer.

Constraints

<var>2 \leq N \leq 200\,000</var>

<var>0 < A_i < 10^4</var>

<var>A_i</var> is given with at most 9 digits after the decimal.

Input

Input is given from Standard Input in the following format.

<var>N</var>
<var>A_1</var>
<var>A_2</var>
<var>\vdots</var>
<var>A_N</var>

Output

Print the number of pairs with integer product <var>A_i \cdot A_j</var> (and <var>i < j</var>).

Sample Input 1

5
7.5
2.4
17.000000001
17
16.000000000

Sample Output 1

3

There are 3 pairs with integer product:

<var>7.5 \cdot 2.4 = 18</var>

<var>7.5 \cdot 16 = 120</var>

<var>17 \cdot 16 = 272</var>

Sample Input 2

11
0.9
1
1
1.25
2.30000
5
70
0.000000001
9999.999999999
0.999999999
1.000000001

Sample Output 2

8


n=int(input())
l=[]
for i in range(0,n):
  x=eval(input())
  l.append(x)
c=0
for i in range(0,n):
  for j in range(i+1,n):
    x=l[i]*l[j]
    if int(x)==x:
      c=c+1
print(c)


import sys
sys.setrecursionlimit(10**8)
from collections import defaultdict,Counter
def dfs(ans, cnts):
    L = []
    d = defaultdict(list)
    heads = defaultdict(int)
    for s,c in cnts:
        if len(s)==1:
            L.append(s[0])
        else:
            for k,v in c.items():
                if v>0:
                    heads[k] += 1
            t = s[-1]
            c[t] -= 1
            s.pop()
            d[t].append([s,c])
    for h in L:
        ans += heads[h]
    for v in d.values():
        if len(v)<=1:
            continue
        ans = dfs(ans, v)
    return ans

N = int(input())
S = [list(input()) for _ in range(N)]
cnts = []
for s in S:
    cnts.append([s,Counter(s)])
ans = dfs(0, cnts)
print(ans)

import sys
input = sys.stdin.readline

def solve():
    N = int(input())
    S = [input().rstrip()[::-1] for i in range(N)]
    S.sort(key=len)
    P = 2**61 - 1

    from collections import defaultdict
    D = defaultdict(lambda: [0]*26)

    ans = 0
    for s in S:
        l = ord(s[-1]) - ord('a')
        a = 0
        tmp = [0] * 26
        for c in s[:-1]:
            i = ord(c) - ord('a')
            if a in D:
                for j in range(26):
                    tmp[j] += D[a][j]
            ans += tmp[i]
            tmp[i] = 0
            a = (a*27 + i + 1) % P
        ans += tmp[l]
        D[a][l] += 1

    print(ans)
solve()

Score : <var>700</var> points

Problem Statement

Limak can repeatedly remove one of the first two characters of a string,
    for example <var>abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx</var>.

You are given <var>N</var> different strings <var>S_1, S_2, \ldots, S_N</var>.
Among <var>N \cdot (N-1) / 2</var> pairs <var>(S_i, S_j)</var>,
    in how many pairs could Limak obtain one string from the other?

Constraints

<var>2 \leq N \leq 200\,000</var>

<var>S_i</var> consists of lowercase English letters a-z.

<var>S_i \neq S_j</var>

<var>1 \leq |S_i|</var>

<var>|S_1| + |S_2| + \ldots + |S_N| \leq 10^6</var>

Input

Input is given from Standard Input in the following format.

<var>N</var>
<var>S_1</var>
<var>S_2</var>
<var>\vdots</var>
<var>S_N</var>

Output

Print the number of unordered pairs <var>(S_i, S_j)</var>
    where <var>i \neq j</var> and Limak can obtain one string from the other.

Sample Input 1

3
abcxyx
cyx
abc

Sample Output 1

1

The only good pair is <var>(abcxyx, cyx)</var>.

Sample Input 2

6
b
a
abc
c
d
ab

Sample Output 2

5

There are five good pairs: <var>(b, abc)</var>, <var>(a, abc)</var>, <var>(abc, c)</var>, <var>(b, ab)</var>, <var>(a, ab)</var>.


# a = tuple(int(sys.stdin.readline()) for _ in range(N)) # multi line with single param
# a = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(N)) # multi line with multi param
# s = sys.stdin.readline().rstrip()
# N = int(sys.stdin.readline())
# INF = float("inf")
import sys,collections
N = int(sys.stdin.readline())
a = tuple(sys.stdin.readline().rstrip()[::-1] for _ in range(N)) # multi line with single param

root = {"children":{},"count":0}

for s in a:
    n = root
    n["count"] += 1
    for c in s:
        if not c in n["children"]:
            n["children"][c] = {"children":{},"count":0}
        n = n["children"][c]
        n["count"] += 1
    n["stop"] = s

#print(root)

def count(s):
    k = len(s)
    n = root
    i = 0
    for c in s[:-1]:
        #print(c,n)
        if not c in n["children"]:
            return 0
        n = n["children"][c]
    return n["count"]

print(sum(1 for b in [count(s) for s in a] if b>1))
#print(sum(count(s) for s in a))


import os
import sys

import numpy as np

def solve(inp):
    n = inp[0]
    xxx = inp[1::2]
    yyy = inp[2::2]
    xxx_idx = np.argsort(xxx)
    yyy_idx = np.argsort(yyy)
    # print('xxx_idx', xxx_idx)
    # print('yyy_idx', yyy_idx)
    xxx_num = np.argsort(xxx_idx)
    yyy_num = np.argsort(yyy_idx)

    # print('xxx_num', xxx_num)
    # print('yyy_num', yyy_num)

    # i: 入力順のルークの番号
    # xi: x座標昇順にソートしたときの順番
    # xxx_idx[xi] = i
    # xxx_num[i] = xi

    def get_xy_by_xi(xi):
        i = xxx_idx[xi]
        return xxx[i], yyy[i]

    def calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, rnxi, rook_cnt):
        lpx, lpy = get_xy_by_xi(lpxi)
        rnx, rny = get_xy_by_xi(rnxi)

        diag_t = abs(rnx - lpx) + abs(rny - lpy) - rook_cnt

        lllt = llt + abs(rnx - lx) + abs(rny - ly) + diag_t
        llrt = llt + abs(lx - lpx) + abs(ly - lpy) + diag_t
        lrlt = lrt + abs(rnx - rx) + abs(rny - ry) + diag_t
        lrrt = lrt + abs(rx - lpx) + abs(ry - lpy) + diag_t
        rllt = rlt + abs(rnx - lx) + abs(rny - ly) + diag_t
        rlrt = rlt + abs(lx - lpx) + abs(ly - lpy) + diag_t
        rrlt = rrt + abs(rnx - rx) + abs(rny - ry) + diag_t
        rrrt = rrt + abs(rx - lpx) + abs(ry - lpy) + diag_t

        llt = min(lllt, lrlt)
        lrt = min(llrt, lrrt)
        rlt = min(rllt, rrlt)
        rrt = min(rlrt, rrrt)
        # print('upd', lpx, lpy, rnx, rny)
        # print('upd', llt, lrt, rlt, rrt)
        # print('upd', lllt, llrt, lrlt, lrrt, rllt, rlrt, rrlt, rrrt)

        return lpx, lpy, rnx, rny, llt, lrt, rlt, rrt

    # free[xi] = xi+1 のルークと初期状態から互いに取り合える関係にあるか(0/1)
    free = np.zeros(n, dtype=np.int8)

    for i in range(n):
        xi = xxx_num[i]
        yi = yyy_num[i]
        px_i = -1 if xi == 0 else xxx_idx[xi - 1]
        nx_i = -2 if xi == n - 1 else xxx_idx[xi + 1]
        py_i = -3 if yi == 0 else yyy_idx[yi - 1]
        ny_i = -4 if yi == n - 1 else yyy_idx[yi + 1]
        if px_i == py_i or px_i == ny_i:
            free[xi - 1] = 1
        if nx_i == py_i or nx_i == ny_i:
            free[xi] = 1

    # freeが連続する箇所は、どこから始めても互いに全て取り合える
    # これを「グループ」とする
    # グループの左端と右端のxiを求める
    free_l = np.zeros(n, dtype=np.int64)
    free_r = np.zeros(n, dtype=np.int64)
    l = 0
    for xi in range(n - 1):
        if free[xi] == 0:
            l = xi + 1
        free_l[xi + 1] = l
    r = n - 1
    free_r[r] = r
    for xi in range(n - 2, -1, -1):
        if free[xi] == 0:
            r = xi
        free_r[xi] = r

    # print(free)
    # print(free_l)
    # print(free_r)

    # グループ内のルークを全部取った時点を0として、追加で取れるルークを取るのにかかる時間
    # グループ内のルークを取り終わったのが、左端、右端のいずれかで2通り計算
    # 同グループに属するルークはこの情報を共有できるので、一番左端のルークの位置に記録
    # Key: xi
    extra_l = np.zeros(n, dtype=np.int64)
    extra_r = np.zeros(n, dtype=np.int64)
    INF = 10 ** 18
    lxi = 0
    while lxi < n:
        rxi = free_r[lxi]

        if lxi == rxi:
            lxi = rxi + 1
            continue

        li = xxx_idx[lxi]
        ri = xxx_idx[rxi]
        lyi = yyy_num[li]
        ryi = yyy_num[ri]
        lyi, ryi = min(lyi, ryi), max(lyi, ryi)

        original_li = lxi
        lx = xxx[li]
        ly = yyy[li]
        rx = xxx[ri]
        ry = yyy[ri]
        llt, lrt, rlt, rrt = 0, INF, INF, 0

        # print('li', li, 'ri', ri, 'lxi', lxi, 'lyi', lyi, 'rxi', rxi, 'ryi', ryi)

        while True:
            px_i = -1 if lxi == 0 else xxx_idx[lxi - 1]
            py_i = -2 if lyi == 0 else yyy_idx[lyi - 1]
            nx_i = -3 if rxi == n - 1 else xxx_idx[rxi + 1]
            ny_i = -4 if ryi == n - 1 else yyy_idx[ryi + 1]
            # print(px_i, py_i, nx_i, ny_i)
            if px_i == py_i:
                lpxi = free_l[lxi - 1]
                rook_cnt = lxi - lpxi

                if nx_i == ny_i:
                    rnxi = free_r[rxi + 1]
                    rook_cnt += rnxi - rxi
                    # print(0, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
                    lx, ly, rx, ry, llt, lrt, rlt, rrt = \
                        calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, rnxi, rook_cnt)
                    lxi = lpxi
                    rxi = rnxi
                    uyi = yyy_num[xxx_idx[lxi]]
                    vyi = yyy_num[xxx_idx[rxi]]
                    lyi, ryi = min(lyi, ryi, uyi, vyi), max(lyi, ryi, uyi, vyi)
                    # print(0, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
                else:
                    # print(1, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
                    lx, ly, rx, ry, llt, lrt, rlt, rrt = \
                        calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, lpxi, rook_cnt)
                    lxi = lpxi
                    uyi = yyy_num[xxx_idx[lxi]]
                    lyi, ryi = min(lyi, ryi, uyi), max(lyi, ryi, uyi)
                    # print(1, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)

            elif px_i == ny_i:
                lpxi = free_l[lxi - 1]
                rook_cnt = lxi - lpxi

                if nx_i == py_i:
                    rnxi = free_r[rxi + 1]
                    rook_cnt += rnxi - rxi
                    # print(2, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
                    lx, ly, rx, ry, llt, lrt, rlt, rrt = \
                        calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, rnxi, rook_cnt)
                    lxi = lpxi
                    rxi = rnxi
                    uyi = yyy_num[xxx_idx[lxi]]
                    vyi = yyy_num[xxx_idx[rxi]]
                    lyi, ryi = min(lyi, ryi, uyi, vyi), max(lyi, ryi, uyi, vyi)
                    # print(2, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
                else:
                    # print(3, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, llt, lrt, rlt, rrt)
                    lx, ly, rx, ry, llt, lrt, rlt, rrt = \
                        calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, lpxi, rook_cnt)
                    lxi = lpxi
                    uyi = yyy_num[xxx_idx[lxi]]
                    lyi, ryi = min(lyi, ryi, uyi), max(lyi, ryi, uyi)
                    # print(3, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, llt, lrt, rlt, rrt)

            elif nx_i == ny_i or nx_i == py_i:
                rnxi = free_r[rxi + 1]
                rook_cnt = rnxi - rxi
                # print(4, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
                lx, ly, rx, ry, llt, lrt, rlt, rrt = \
                    calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, rnxi, rnxi, rook_cnt)
                rxi = rnxi
                vyi = yyy_num[xxx_idx[rxi]]
                lyi, ryi = min(lyi, ryi, vyi), max(lyi, ryi, vyi)
                # print(4, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)

            else:
                extra_l[original_li] = min(llt, lrt)
                extra_r[original_li] = min(rlt, rrt)
                break

        lxi = rxi + 1

    # print(extra_l)
    # print(extra_r)

    ans = np.zeros(n, dtype=np.int64)
    for i in range(n):
        xi = xxx_num[i]
        x = xxx[i]
        y = yyy[i]
        lxi = free_l[xi]
        lx = xxx[xxx_idx[lxi]]
        ly = yyy[xxx_idx[lxi]]
        rxi = free_r[xi]
        rx = xxx[xxx_idx[rxi]]
        ry = yyy[xxx_idx[rxi]]
        lt = extra_l[lxi]
        rt = extra_r[lxi]
        diag = abs(rx - lx) + abs(ry - ly) - (rxi - lxi)
        rlt = abs(rx - x) + abs(ry - y) + diag
        lrt = abs(x - lx) + abs(y - ly) + diag
        ans[i] = min(lt + rlt, rt + lrt)

    return ans

if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', '(i8[:],)')(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    # noinspection PyUnresolvedReferences
    from my_module import solve
else:
    from numba import njit

    solve = njit('(i8[:],)', cache=True)(solve)
    print('compiled', file=sys.stderr)

inp = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=' ')
ans = solve(inp)
print('\n'.join(map(str, ans)))

Score : <var>2200</var> points

Problem Statement

You are given positions <var>(X_i, Y_i)</var> of <var>N</var> enemy rooks on an infinite chessboard.
No two rooks attack each other (at most one rook per row or column).

You're going to replace one rook with a king and then move the king repeatedly to beat as many rooks as possible.

You can't enter a cell that is being attacked by a rook.
Additionally, you can't move diagonally to an empty cell (but you can beat a rook diagonally).

(So this king moves like a superpawn that beats diagonally in 4 directions and moves horizontally/vertically in 4 directions.)

For each rook, consider replacing it with a king, and find the minimum possible number of moves
    needed to beat the maximum possible number of rooks.

Constraints

<var>2 \leq N \leq 200\,000</var>

<var>1 \leq X_i, Y_i \leq 10^6</var>

<var>X_i \neq X_j</var>

<var>Y_i \neq Y_j</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format.

<var>N</var>
<var>X_1</var> <var>Y_1</var>
<var>X_2</var> <var>Y_2</var>
<var>\vdots</var>
<var>X_N</var> <var>Y_N</var>

Output

Print <var>N</var> lines.
The <var>i</var>-th line is for scenario of replacing the rook at <var>(X_i, Y_i)</var> with your king.
This line should contain one integer: the minimum number of moves to beat <var>M_i</var> rooks
    where <var>M_i</var> denotes the maximum possible number of beaten rooks in this scenario (in infinite time).

Sample Input 1

6
1 8
6 10
2 7
4 4
9 3
5 1

Sample Output 1

5
0
7
5
0
0

See the drawing below.
If we replace rook 3 with a king, we can beat at most two other rooks.
The red path is one of optimal sequences of moves: beat rook 1,
    then keep going down and right until you can beat rook 4.
There are 7 steps and that's the third number in the output.

x-coordinate increases from left to right,
    while y increases bottom to top.

Starting from rook 2, 5 or 6, we can't beat any other rook.
The optimal number of moves is 0.

Sample Input 2

5
5 5
100 100
70 20
81 70
800 1

Sample Output 2

985
985
1065
1034
0

Sample Input 3

10
2 5
4 4
13 12
12 13
14 17
17 19
22 22
16 18
19 27
25 26

Sample Output 3

2
2
9
9
3
3
24
5
0
25