Problem:


Score : 600 points

Problem Statement

We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates.

For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate axes, that contains all the points in T. More formally, we define f(T) as follows:

f(T) :=  (the number of integers i (1 \leq i \leq N) such that a \leq x_i \leq b and c \leq y_i \leq d, where a, b, c, and d are the minimum x-coordinate, the maximum x-coordinate, the minimum y-coordinate, and the maximum y-coordinate of the points in T)

Find the sum of f(T) over all non-empty subset T of S. Since it can be enormous, print the sum modulo 998244353.

Constraints

1 \leq N \leq 2 \times 10^5

-10^9 \leq x_i, y_i \leq 10^9

x_i \neq x_j (i \neq j)

y_i \neq y_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the sum of f(T) over all non-empty subset T of S, modulo 998244353.

Sample Input 1

3
-1 3
2 1
3 -2

Sample Output 1

13

Let the first, second, and third points be P_1, P_2, and P_3, respectively. S = \{P_1, P_2, P_3\} has seven non-empty subsets, and f has the following values for each of them:

f(\{P_1\}) = 1

f(\{P_2\}) = 1

f(\{P_3\}) = 1

f(\{P_1, P_2\}) = 2

f(\{P_2, P_3\}) = 2

f(\{P_3, P_1\}) = 3

f(\{P_1, P_2, P_3\}) = 3

The sum of these is 13.

Sample Input 2

4
1 4
2 1
3 3
4 2

Sample Output 2

34

Sample Input 3

10
19 -11
-3 -12
5 3
3 -15
8 -14
-9 -20
10 -9
0 2
-7 17
6 -6

Sample Output 3

7222

Be sure to print the sum modulo 998244353.



Sample input:
3
-1 3
2 1
3 -2


Sample output:
13

Submission status: Accepted

Solution code:
def f_encolsed_points(MOD=998244353):
    # 参考: https://atcoder.jp/contests/abc136/submissions/6696160
    import sys
    input = sys.stdin.readline

    class BIT(object):
        """Binary Indexed Tree (1-indexed)"""

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

        def sum(self, index):
            """tree[1]からtree[index]までの和を計算"""
            ret = 0
            while index > 0:
                ret += self.tree[index]
                index -= index & (-index)
            return ret

        def add(self, index, value=1):
            """tree[index]にvalueを加算"""
            while index <= self.size:
                self.tree[index] += value
                index += index & (-index)

    N = int(input())
    Pos = [[int(i) for i in input().split()] for j in range(N)]

    Pos.sort()  # x座標でソートする
    _, pos_y = zip(*Pos)
    y_comp = {y: i for i, y in enumerate(sorted(pos_y), 1)}  # y座標を圧縮

    pow_2 = [1]
    for _ in range(N):
        pow_2.append(pow_2[-1] * 2 % MOD)

    ans = 0
    tree = BIT(N)
    # x座標が小さな点から順に考える
    for left, (_x, _y) in enumerate(Pos):
        y = y_comp[_y]

        # それぞれ、注目している点の 右|下|上 にいくつ点が存在するか
        right = N - 1 - left
        down = y - 1
        up = N - 1 - down

        lower_left = tree.sum(y)
        tree.add(y, 1)
        upper_left = left - lower_left
        lower_right = down - lower_left
        upper_right = right - lower_right

        # 包除原理(全体 - 上下左右 + 左上左下右上右下 - それ自体)
        count = (pow_2[N]
                 - (pow_2[up] + pow_2[down] + pow_2[left] + pow_2[right])
                 + (pow_2[upper_left] + pow_2[lower_left] + pow_2[upper_right] + pow_2[lower_right])
                 - 1)
        ans += count
        ans %= MOD
    return ans

print(f_encolsed_points())

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
"""
Binary indexed tree
0-indexed, 関数は閉区間
0からの区間加算、1点更新
"""
class BIT: #0-indexed
    def __init__(self, n):
        self.tree = [0]*(n+1)
        self.tree[0] = None
#        self.element = [0]*(n+1)
    def sum(self, i): #a_0 + ... + a_{i} #閉区間
        s = 0; i += 1
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
    def range(self,l,r): #a_l + ... + a_r 閉区間
        return sum(r) - sum(l-1) 
    def add(self, i, x):
        i += 1
        while i <= n:
            self.tree[i] += x
            i += i & -i
        # self.element[i] += x
    #def get(self,i): return element[i]        
    
###########################################

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n = int(input())
xyi = [[int(i) for i in readline().split()]+[j] for j in range(n)]
#xyi = []
#for i in range(n):
#    a = [int(i) for i in readline().split()]
#    xyi.append(a+[i])

#dame_x = [0]*n
#dame_y = [0]*n
#dame_xy = [0]*n

ABi = [0]*n
CDi = [0]*n

MOD = 998244353

sxyi = sorted(xyi, key = lambda x: x[1])
zaatu = [0]*n
for j in range(n): zaatu[sxyi[j][2]] = j
for j, (x,y,i) in enumerate(sxyi):
    ABi[i] = n-j-1
    CDi[i] = j

pow2 = [1]*(n+1)
for i in range(n):
    pow2[i+1] = pow2[i]*2%MOD


xyi.sort()
#print(pow2)

bit = BIT(n)

ans = n*(pow2[n]-1)%MOD
for j, (x,y,i) in enumerate(xyi):
    AB = ABi[i]
    CD = CDi[i]
    BC = j
    AD = n-j-1
    c = bit.sum(zaatu[i])
    C = c
    B = j-c
#    print(AB-B,B,C,CD-C)
    ans -= pow2[AB]-1 + pow2[CD]-1 
    ans -= pow2[BC]-1 + pow2[AD]-1
    ans += pow2[C]-1 + pow2[CD-C]-1 + pow2[B]-1 + pow2[AB-B]-1

    bit.add(zaatu[i],1)
        

        


print(ans%MOD)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
"""
Binary indexed tree
0-indexed, 関数は閉区間
0からの区間加算、1点更新
"""
class BIT: #0-indexed
    def __init__(self, n):
        self.tree = [0]*(n+1)
        self.tree[0] = None
#        self.element = [0]*(n+1)
    def sum(self, i): #a_0 + ... + a_{i} #閉区間
        s = 0; i += 1
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
    def range(self,l,r): #a_l + ... + a_r 閉区間
        return sum(r) - sum(l-1) 
    def add(self, i, x):
        i += 1
        while i <= n:
            self.tree[i] += x
            i += i & -i
        # self.element[i] += x
    #def get(self,i): return element[i]        
    
###########################################
# http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=3791366
###########################################

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n = int(input())
xyi = [[int(i) for i in readline().split()]+[j] for j in range(n)]
#xyi = []
#for i in range(n):
#    a = [int(i) for i in readline().split()]
#    xyi.append(a+[i])

dame_x = [0]*n
dame_y = [0]*n
dame_xy = [0]*n

MOD = 998244353

sxyi = sorted(xyi, key = lambda x: x[1]) # zaatu の逆写像
modosu = [i for x,y,i in sxyi]
zaatu = [0]*n
for j,zj in enumerate(modosu):
    zaatu[zj] = j

pow2 = [1]*(n+1)
for i in range(n):
    pow2[i+1] = pow2[i]*2%MOD

for j, (x,y,i) in enumerate(sxyi):
    dame_y[i] = pow2[j]-1 + pow2[n-j-1]-1

xyi.sort()
#print(pow2)

bit = BIT(n)
for j, (x,y,i) in enumerate(xyi):
    dame_x[i] = pow2[j] -1 + pow2[n-j-1]-1
    c = bit.sum(zaatu[i])
    dame_xy[i] += pow2[c]-1 + pow2[j-c]-1
    bit.add(zaatu[i],1)
        
bit = BIT(n)
for j, (x,y,i) in enumerate(reversed(xyi)):
    c = bit.sum(zaatu[i])
    dame_xy[i] += pow2[c]-1 + pow2[j-c]-1
    bit.add(zaatu[i],1)
        
        
#print(dame_x,"\n",dame_y,"\n",dame_xy)

ans = n*(pow2[n]-1)%MOD
for dx,dy,dxy in zip(dame_x,dame_y,dame_xy):
    ans += - dx - dy + dxy


print(ans%MOD)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
"""
Binary indexed tree
0-indexed, 関数は閉区間
0からの区間加算、1点更新
"""
class BIT: #0-indexed
    def __init__(self, n):
        self.tree = [0]*(n+1)
        self.tree[0] = None
#        self.element = [0]*(n+1)
    def sum(self, i): #a_0 + ... + a_{i} #閉区間
        s = 0; i += 1
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
    def range(self,l,r): #a_l + ... + a_r 閉区間
        return sum(r) - sum(l-1) 
    def add(self, i, x):
        i += 1
        while i <= n:
            self.tree[i] += x
            i += i & -i
        # self.element[i] += x
    #def get(self,i): return element[i]        
    
###########################################
# http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=3791366
###########################################

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n = int(input())
xyi = []
for i in range(n):
    a = [int(i) for i in readline().split()]
    xyi.append(a+[i])

dame_x = [0]*n
dame_y = [0]*n
dame_xy = [0]*n

MOD = 998244353

sxyi = sorted(xyi, key = lambda x: x[1]) # zaatu の逆写像
modosu = [i for x,y,i in sxyi]
zaatu = [0]*n
for j,zj in enumerate(modosu):
    zaatu[zj] = j

pow2 = [1]*(n+1)
for i in range(n):
    pow2[i+1] = pow2[i]*2%MOD

for j, (x,y,i) in enumerate(sxyi):
    dame_y[i] = pow2[j]-1 + pow2[n-j-1]-1

xyi.sort()
#print(pow2)

bit = BIT(n)
for j, (x,y,i) in enumerate(xyi):
    dame_x[i] = pow2[j] -1 + pow2[n-j-1]-1
    c = bit.sum(zaatu[i])
    dame_xy[i] += pow2[c]-1 + pow2[j-c]-1
    bit.add(zaatu[i],1)
        
bit = BIT(n)
for j, (x,y,i) in enumerate(reversed(xyi)):
    c = bit.sum(zaatu[i])
    dame_xy[i] += pow2[c]-1 + pow2[j-c]-1
    bit.add(zaatu[i],1)
        
        
#print(dame_x,"\n",dame_y,"\n",dame_xy)

ans = n*(pow2[n]-1)%MOD
for dx,dy,dxy in zip(dame_x,dame_y,dame_xy):
    ans += - dx - dy + dxy


print(ans%MOD)

Submission status: Accepted

Solution code:
from operator import itemgetter

class BIT:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

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

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

mod = 998244353

N = int(input())
xy = [list(map(int,input().split())) for _ in range(N)]
xy.sort(key=itemgetter(1))
for i in range(N):
    xy[i][1] = i
xy.sort(key=itemgetter(0))

pow2 = [1]*(N+1)
for i in range(N):
    pow2[i+1] = 2*pow2[i]%mod

ans = pow2[N-1]*N%mod

bit = BIT(N)
for i in range(N):
    l1 = bit.sum(xy[i][1])
    l2 = i-l1
    r1 = xy[i][1]-l1
    r2 = N-xy[i][1]-l2-1
    bit.add(xy[i][1],1)
    ans += (pow2[l2]-1)*(pow2[r1]-1)*pow2[r2]*pow2[l1]
    ans += (pow2[r2]-1)*(pow2[l1]-1)*(pow2[l2]+pow2[r1]-1)
    ans %= mod

print(ans)

Submission status: Accepted

Solution code:
from operator import itemgetter

class BIT:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    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

mod = 998244353

N = int(input())
xy = [list(map(int,input().split())) for _ in range(N)]
xy.sort(key=itemgetter(1))
for i in range(N):
    xy[i][1] = i+1
xy.sort(key=itemgetter(0))

pow2 = [1]*(N+1)
for i in range(N):
    pow2[i+1] = 2*pow2[i]%mod

ans = pow2[N-1]*N%mod

bit = BIT(N)
for i in range(N):
    l1 = bit.sum(xy[i][1])
    l2 = i-l1
    r1 = xy[i][1]-l1-1
    r2 = N-xy[i][1]-l2
    bit.add(xy[i][1],1)
    ans += (pow2[l2]-1)*(pow2[r1]-1)*pow2[r2]*pow2[l1]
    ans += (pow2[r2]-1)*(pow2[l1]-1)*(pow2[l2]+pow2[r1]-1)
    ans %= mod

print(ans)

Submission status: Accepted

Solution code:
class BIT:
  ini = 0
  def __init__(self, num):
    self.N = 1
    while self.N <= num:
      self.N *= 2
    self.T = [self.ini] * self.N
  def do(self, l, r):
    #合計
    return l + r
  def set(self, L):
    for i in range(len(L)):
      self.update(i, L[i])
  def update(self, x):
    k = x + 1
    self.T[k - 1] += 1
    k += k & -k
    while k <= N:
      self.T[k - 1] += 1
      k += k & -k
  def getV(self, x):
    ans = self.T[x - 1]
    x -= x & -x
    while x != 0:
      ans += self.T[x - 1]
      x -= x & -x
    return ans

import sys
input = sys.stdin.readline
N = int(input())
xy = [list(map(int, input().split())) for i in range(N)]
MOD = 998244353

xy.sort(key = lambda x:x[1])
R = {}
for i in range(N):
  R[xy[i][1]] = i
xy.sort()

LU = [0] * N
LD = [0] * N
RU = [0] * N
RD = [0] * N

Sl = BIT(N)
for i in range(N):
  t = Sl.getV(R[xy[i][1]])
  LU[i] = i - t
  LD[i] = t
  Sl.update(R[xy[i][1]])

Sr = BIT(N)
for i in range(N-1 , -1 , -1):
  t = Sr.getV(R[xy[i][1]])
  RU[i] = (N - 1 - i) - t
  RD[i] = t
  Sr.update(R[xy[i][1]])

ans = 0
PL = [1]
for i in range(N + 1):
  PL.append(PL[-1] * 2 % MOD)

def na(x):
  return PL[x] - 1

for i in range(N):
  t = PL[N - 1]
  t = (t + na(LU[i]) * na(RD[i])) % MOD
  t = (t + na(LD[i]) * na(RU[i])) % MOD
  t = (t + na(LU[i]) * na(LD[i]) * na(RU[i])) % MOD
  t = (t + na(LU[i]) * na(LD[i]) * na(RD[i])) % MOD
  t = (t + na(LU[i]) * na(RD[i]) * na(RU[i])) % MOD
  t = (t + na(LD[i]) * na(RD[i]) * na(RU[i])) % MOD
  t = (t + na(LU[i]) * na(LD[i]) * na(RD[i]) * na(RU[i])) % MOD
  ans = (ans + t) % MOD

print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left as bl
N = int(input())
P = 998244353
NN = 18
XX = [0] * (2**(NN+1)-1)
pow2 = [1]
for _ in range(1, 202020):
    pow2.append(pow2[-1]*2%P)

def addvalue(j):
    i = 2**NN + j - 1
    while i >= 0:
        XX[i] += 1
        i = (i-1) // 2

def rangesum(a, b):
    l = a + (1<<NN)
    r = b + (1<<NN)
    s = 0
    while l < r:
        if l%2:
            s += XX[l-1]
            l += 1
        if r%2:
            r -= 1
            s += XX[r-1]
        l >>= 1
        r >>= 1
    return s

X = []
Y = []
XY = []
for _ in range(N):
    x, y = map(int, input().split())
    X.append(x)
    Y.append(y)
    XY.append((x, y))

X = sorted(X)
Y = sorted(Y)
XY = sorted(XY, key = lambda x: x[1])

DX = {}
for i in range(N):
    DX[X[i]] = i

ans = 0
U = 0
for x, y in XY:
    a = rangesum(0, DX[x])
    L = bl(X, x)
    b = U-a
    d = L-a
    c = N-a-b-d-1
    ans = (ans + pow2[N] - (pow2[a+b] + pow2[b+c] + pow2[c+d] + pow2[d+a] - pow2[a] - pow2[b] - pow2[c] - pow2[d] + 1)) % P
    U += 1
    addvalue(DX[x])
    
print(ans)

Submission status: Accepted

Solution code:
import sys


class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    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


MOD = 998244353
n = int(input())
xys = []
ys = []
for line in sys.stdin:
    x, y = map(int, line.split())
    xys.append((x, y))
    ys.append(y)
ys.sort()
y_dict = {y: i + 1 for i, y in enumerate(ys)}
xys = [(x, y_dict[y]) for x, y in xys]
xys.sort()
f_bit = Bit(n)
b_bit = Bit(n)
for i in range(1, n + 1):
    b_bit.add(i, 1)

p2d = [1]
for i in range(n):
    p2d.append(p2d[-1] * 2 % MOD)

ans = 0
for i, (x, y) in enumerate(xys):
    b_bit.add(y, -1)
    a = f_bit.sum(y)
    b = i - a
    c = b_bit.sum(y)
    d = (n - i - 1) - c
    f_bit.add(y, 1)
    # print(i, x, y, a, b, c, d)
    pa, pb, pc, pd = p2d[a], p2d[b], p2d[c], p2d[d]
    tmp = p2d[n - 1]
    tmp += (pa - 1) * (pd - 1) * pb * pc
    tmp += (pb - 1) * (pc - 1) * pa * pd
    tmp -= (pa - 1) * (pb - 1) * (pc - 1) * (pd - 1)
    ans = (ans + tmp) % MOD
print(ans)

Submission status: Accepted

Solution code:
import sys
from operator import itemgetter

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n = ni()

co = []
for i in range(n):
    co.append(na())

co.sort(key=itemgetter(1))
for i in range(n):
    co[i][1] = i

# print(co)
ft = [0] * (n + 5)

co.sort(key=itemgetter(0), reverse=True)

ups = [0] * n
downs = [0] * n

def addfenwick(ft, i, v):
    if v == 0 or i < 0: return
    i += 1
    while i < len(ft):
        ft[i] += v
        i += i&-i

def sumfenwick(ft, i):
    s = 0
    i += 1
    while i > 0:
        s += ft[i]
        i -= i&-i
    return s

for i in range(n):
    c = co[i]
    downs[n-1-i] = sumfenwick(ft, c[1])
    ups[n-1-i] = i - downs[n-1-i]
    addfenwick(ft, c[1], 1)

ft = [0] * (n+5)
co = co[::-1]

mod = 998244353
ps = [0] * (n+5)
ps[0] = 1
for i in range(1, n+4):
    ps[i] = ps[i-1] * 2 % mod

ans = 0
for i in range(n):
    c = co[i]
    d = sumfenwick(ft, c[1])
    u = i - d

    # print(d, u, ups[i], downs[i])
    ans += (ps[d]-1) * (ps[ups[i]]-1) * ps[u+downs[i]]
    ans += (ps[u]-1) * (ps[downs[i]]-1) * ps[d+ups[i]]
    ans -= (ps[d]-1) * (ps[ups[i]]-1) * (ps[downs[i]]-1) * (ps[u]-1)
    ans += ps[n-1]
    addfenwick(ft, c[1], 1)

ans %= mod
if ans < 0:
    ans += mod
print(ans)

Submission status: Runtime Error

Solution code:
# 解説放送の方針
# 平面走査をし、各点について、左上、左下、右上、右下にある点を数え、計算する。
# 解説放送ではBITを2本使っていたが、座標圧縮の結果を利用してBIT１本で済むようにした

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

class BIT:
    '''https://tjkendev.github.io/procon-library/python/range_query/bit.html'''
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)
        self.el = [0]*(n+1)
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s
    def add(self, i, x):
        self.el[i] += x
        while i <= self.n:
            self.data[i] += x
            i += i & -i
    def query(self, i, j=None):
        if j is None:
            return self.el[i]
        return self.sum(j) - self.sum(i)

# 平面走査のためのソート（高速化のため１次元にしてソート）
xy2 = []
for i in range(N):
  x,y = xy[i]
  x += 10**9
  y += 10**9
  xy2.append(y<<60 | x << 30 | i)

# ソート後の復元+座標圧縮用の辞書作成
# 座標圧縮: 小さいyから順に1,2,3...と値を割り振る。
xy2 = sorted(xy2)
mask = (1<<30)-1
y_order=[0]*N
y_compress={}
for j,y in enumerate(xy2):
  i = y & mask
  y >>= 30
  x = y & mask
  x -= 10**9
  y >>= 30
  y -= 10**9
  y_order[i] = j
  y_compress[y] = j+1

xy2 = []
for i in range(N):
  x,y = xy[i]
  x += 10**9
  y += 10**9
  xy2.append(x<<60 | y << 30 | i)
  
xy2 = sorted(xy2)
mask = (1<<30)-1
bit=BIT(N)
ans = 0
for x in xy2:
  i = x & mask
  x >>= 30
  y = x & mask
  y -= 10**9
  x >>= 30
  x -= 10**9
  
  y = y_compress[y]
  bit.add(y,1)
  '''
  今現在みている点より左上と左下にある点の個数（今の点は含まない。以下同じ）。
  BITを使って求める。
  '''
  n1 = bit.query(y-1,N)-1
  n2 = bit.query(0,y)-1 
  '''
  右上と右下。座標圧縮の結果を利用。(N-y(座標圧縮済))はある点より上にある点の総数。
  そこからn1（走査済みの点の個数)を引くことで、まだ走査していない点の個数を求めることができる。
  '''
  n3 = N-y-n1 
  n4 = y-n2-1
  prod14 = (pow(2,n1,mod)-1)*(pow(2,n4,mod)-1)*pow(2,n2+n3,mod) %mod
  prod23 = (pow(2,n2,mod)-1)*(pow(2,n3,mod)-1)*pow(2,n1+n4,mod) %mod
  prod1234 = (pow(2,n1,mod)-1)*(pow(2,n4,mod)-1)*(pow(2,n2,mod)-1)*(pow(2,n3,mod)-1) %mod
  ans += pow(2,N-1,mod)+prod14+prod23-prod1234
  ans %= mod
  
print(ans)

Submission status: Runtime Error

Solution code:
from copy import copy, deepcopy
# from functools import reduce
# from heapq import heapify, heappop, heappush
# from itertools import accumulate, permutations, combinations, combinations_with_replacement, groupby, product
import unittest
from io import StringIO
import math
# import numpy as np  # Pythonのみ！
# from operator import xor
# import re
# from scipy.sparse.csgraph import connected_components  # Pythonのみ！
# ↑cf.  https://note.nkmk.me/python-scipy-connected-components/
# from scipy.sparse import csr_matrix
# import string
import sys
sys.setrecursionlimit(10 ** 5 + 10)


def input(): return sys.stdin.readline().strip()


def resolve():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))

    def make_divisors(n):
        divisors = []
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.append(i)
                if i != n // i:  # 平方数の場合n**0.5を1つだけにしてる
                    divisors.append(n//i)

        divisors.sort(reverse=True)  # ソートしたけりゃして
        return divisors

    M = make_divisors(sum(A))

    def main():
        for i in M:
            AA = A.copy()
            age = 0
            delete = 0
            for j in range(N):
                AA[j] = AA[j] % i
                if AA[j] == 0:
                    delete += 1
                    age -= i
                age += i-AA[j]
            AA.sort()

            times = 10**9
            sage = 0
            for j in range(delete, N-1):
                sage += AA[j]
                age -= i-AA[j]
                if sage % i == age % i:
                    times = min(max(sage, age), times)
            if times <= K:
                return i
    print(main())

resolve()

Submission status: Runtime Error

Solution code:
class BIT:
    def __init__(self, N):
        self.size = N
        self.tree = [0] * (N + 1)

    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

N, *XY = map(int, open(0).read().split())
X, Y = XY[::2], XY[1::2]

memo = {y: i for i, y in enumerate(sorted(Y))}
Y = [y for x, y in sorted(zip(X, map(memo.get, Y)), key=lambda p: p[0])]

P = [1]
for i in range(N):
    P.append(P[-1] * 2 % mod)

ans = P[N - 1] * N % mod
bit = BIT(N)
for i, y in enumerate(Y):
    bit.add(y + 1, 1)

    ld = bit.sum(y)
    lu = i - ld

    rd = y - ld
    ru = N - y - 1 - lu

    A, B, C, D = P[ru], P[lu], P[ld], P[rd]

    ans += ((C - 1) * (A - 1) % mod) * (B * D % mod) % mod
    ans += ((B - 1) * (D - 1) % mod) * (C * A % mod) % mod
    ans -= ((C - 1) * (A - 1) % mod) * ((D - 1) * (B - 1) % mod) % mod
    ans %= mod

print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
class BIT:
    def __init__(self, n):
        self.n = n
        self.data = [0] * (n + 1)

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

    def add(self, i, x):
        while i <= self.n:
            self.data[i] += x
            i += i & -i
mod = 998244353
N = int(input())
V = map(int,read().split())
V.sort(key = lambda x:x[1])
Bl = BIT(N)
Br = BIT(N)
for i in range(N):
    V[i][1] = i+1
    Br.add(i+1, 1)
V.sort()
ans = 0
for i in range(N):
    x, y = V[i]
    ld = Bl.sum(y-1)
    lu = i-ld
    rd = Br.sum(y-1)
    ru = (N-i)-rd-1
    Br.add(y, -1)
    Bl.add(y, 1)
    A = pow(2, N-1, mod)
    B = pow(2, lu+rd, mod)*(pow(2, ru, mod)-1)*(pow(2, ld, mod)-1)%mod
    C = pow(2, ru+ld, mod)*(pow(2, lu, mod)-1)*(pow(2, rd, mod)-1)%mod
    BC = (pow(2, ru, mod)-1)*(pow(2, ld, mod)-1)*(pow(2, lu, mod)-1)*(pow(2, rd, mod)-1)%mod
    ans += A+B+C-BC
    ans %= mod
print(ans)

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
class BIT:
    def __init__(self, n):
        self.n = n
        self.data = [0] * (n + 1)

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

    def add(self, i, x):
        while i <= self.n:
            self.data[i] += x
            i += i & -i
mod = 998244353
N = int(input())
V = map(int,read().split())
V.sort(key = lambda x:x[1])
Bl = BIT(N)
Br = BIT(N)
for i in range(N):
    V[i][1] = i+1
    Br.add(i+1, 1)
V.sort()
ans = 0
for i in range(N):
    x, y = V[i]
    ld = Bl.sum(y-1)
    lu = i-ld
    rd = Br.sum(y-1)
    ru = (N-i)-rd-1
    Br.add(y, -1)
    Bl.add(y, 1)
    A = pow(2, N-1, mod)
    B = pow(2, lu+rd, mod)*(pow(2, ru, mod)-1)*(pow(2, ld, mod)-1)%mod
    C = pow(2, ru+ld, mod)*(pow(2, lu, mod)-1)*(pow(2, rd, mod)-1)%mod
    BC = (pow(2, ru, mod)-1)*(pow(2, ld, mod)-1)*(pow(2, lu, mod)-1)*(pow(2, rd, mod)-1)%mod
    ans += A+B+C-BC
    ans %= mod
print(ans)

Submission status: Runtime Error

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

def sub(a, b):
    return (a % mod + mod - b % mod) % mod

n, = list(map(int, input().split()))
t = 1
dd = [t]
for _ in range(n):
    t=2*t%mod
    dd.append(t)

def pow2(b):
    return dd[b]

class SegTree:
    def __init__(self, init_val, n, ide_ele, seg_func):
        self.segfunc = seg_func
        self.num = 2**(n-1).bit_length()
        self.ide_ele = ide_ele
        self.seg=[self.ide_ele]*2*self.num
        for i in range(n):
            self.seg[i+self.num-1]=init_val[i]    
        for i in range(self.num-2,-1,-1) :
            self.seg[i]=self.segfunc(self.seg[2*i+1],self.seg[2*i+2]) 
        
    def update(self, k, x):
        k += self.num-1
        self.seg[k] = x
        while k+1:
            k = (k-1)//2
            self.seg[k] = self.segfunc(self.seg[k*2+1],self.seg[k*2+2])
        
    def query(self, p, q):
        if q<=p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res=self.ide_ele
        while q-p>1:
            if p&1 == 0:
                res = self.segfunc(res,self.seg[p])
            if q&1 == 1:
                res = self.segfunc(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfunc(res,self.seg[p])
        else:
            res = self.segfunc(self.segfunc(res,self.seg[p]),self.seg[q])
        return res

def mm(a, b, c, d, n):
    return sub(pow2(b+c) + pow2(c+d) + pow2(d+a) + pow2(a+b),
                pow2(a) + pow2(b) + pow2(c) + pow2(d))

xs, ys = [], []
for _ in range(n):
    x, y = list(map(int, input().split()))
    xs.append(x)
    ys.append(y)

ini = sorted(list(range(n)), key=lambda x:xs[x])
for i, yi in enumerate(sorted(list(range(n)), key=lambda x:ys[x])):
    ys[yi] = i 
nys = [ys[i] for i in ini]

ss1 = SegTree([0] * n, n, 0, lambda x,y:x+y)
r = 0
for i, y in enumerate(nys):
    ss1.update(y, 1)
    d = ss1.query(0, y)
    c = i - d
    b = (n-1) - y - c
    a = (n-1) - b - c - d
    r = (r + mm(a, b, c, d, n)) % mod

print(sub((power(2, n) * n) % mod, (r+n)%mod))

Submission status: Runtime Error

Solution code:
import itertools
import os
import sys
from collections import defaultdict

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 998244353


class BinaryIndexedTree:
    # http://hos.ac/slides/20140319_bit.pdf
    def __init__(self, size):
        """
        :param int size:
        """
        self._bit = [0] * size
        self._size = size

    def add(self, i, w):
        """
        i 番目に w を加える
        :param int i:
        :param int w:
        :return:
        """
        x = i + 1
        while x <= self._size:
            self._bit[x - 1] += w
            x += x & -x

    def sum(self, i):
        """
        0 番目から i 番目までの合計
        :param int i:
        :return:
        """
        ret = 0
        x = i + 1
        while x > 0:
            ret += self._bit[x - 1]
            x -= x & -x
        return ret

    def __len__(self):
        return self._size


def compress(li):
    """
    大小関係を保ったまま 1 以上の数値に圧縮する。
    scipy.stats.rankdata に近い感じ
    :param list li:
    :rtype: list of int
    """
    ret = [0] * len(li)
    rank = 0
    prev = None
    for a, i in sorted([(a, i) for i, a in enumerate(li)]):
        if a != prev:
            rank += 1
        ret[i] = rank
    return ret


# 解説AC
N = int(sys.stdin.readline())
XY = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]


def test():
    ret = 0
    counts = defaultdict(int)
    for selection in itertools.product([0, 1], repeat=N):
        if not any(selection):
            continue
        xs = set([XY[i][0] for i, s in enumerate(selection) if s])
        ys = set([XY[i][1] for i, s in enumerate(selection) if s])
        xl = min(xs)
        xr = max(xs)
        yl = min(ys)
        yr = max(ys)
        r = 0
        for x, y in XY:
            r += xl <= x <= xr and yl <= y <= yr
        ret += r
        counts[r] += 1
    return ret


XY.sort()
Y = [y for _, y in XY]
Y = compress(Y)

# LL[i]: x が X[i] より小さくて、y が Y[i] より小さい数
# LG[i]: x が X[i] より小さくて、y が Y[i] より大きい数
LL = []
LG = []
GL = []
GG = []

bit = BinaryIndexedTree(size=max(Y) + 1)
for i, y in enumerate(Y):
    ll = bit.sum(y)
    lg = i - ll
    LL.append(ll)
    LG.append(lg)
    bit.add(y, 1)
bit = BinaryIndexedTree(size=max(Y) + 1)
for i, y in enumerate(Y[::-1]):
    gl = bit.sum(y)
    gg = i - gl
    GL.append(gl)
    GG.append(gg)
    bit.add(y, 1)
GL.reverse()
GG.reverse()

pow2 = [1] * N
p = 1
for i in range(N - 1):
    p = p * 2 % MOD
    pow2[i + 1] = p

assert False
# 点 p = (X[i], Y[i]) が何回カウントされるか
ans = 0
for ll, lg, gl, gg in zip(LL, LG, GL, GG):
    # -- p を選ぶ --
    ans += pow2[N - 1]
    # -- p を選ばない --
    # ll, gg をそれぞれ1つ以上選ぶ
    a = (pow2[ll] - 1) * (pow2[gg] - 1) % MOD * pow2[N - ll - gg - 1]
    # lg, gl をそれぞれ1つ以上選ぶ
    b = (pow2[lg] - 1) * (pow2[gl] - 1) % MOD * pow2[N - lg - gl - 1]
    # ll, gg, gl, lg をそれぞれ1つ以上選ぶ
    c = (pow2[ll] - 1) * (pow2[gg] - 1) % MOD * (pow2[lg] - 1) * (pow2[gl] - 1) % MOD
    ans += a + b - c
    ans %= MOD
print(ans)

Submission status: Runtime Error

Solution code:
import sys
import array

from operator import itemgetter

def main():



	input = sys.stdin.readline


	md = 998244353
	n = int(input())
	tl=n+1
	
	ft=[0]*tl

	xy = [[0]*2 for _ in range(n)]
	for i in range(n):
		xy[i] = [int(item) for item in input().split()]
	xy.sort(key=itemgetter(0))
	yxi = [y for x, y in xy]

	*YS, = set(yxi)
	YS.sort()
	yxi= list(map({e: i for i, e in enumerate(YS)}.__getitem__, yxi))

	ct=[0]*(n+1)
	ct[0]=1
	for i in range(1,n+1):
		ct[i]=ct[i-1]*2%md

	cnt=tuple(ct)

	def upd(i):
		i+=1
		while(i<=len(ft)):
			ft[i]+=1
			i+=i&-i

	def get(i):
		i+=1
		ret=0
		while(i!=0):
		    ret+=ft[i]
		    i-=i&-i
		return ret

	def calc(get,upd):
		for i, y in enumerate(yxi):
			v = get(y); upd(y)
			p1 = cnt[v]; p0 = cnt[y - v]
			q1 = cnt[i - v]; q0 = cnt[(n - y - 1) - (i - v)]
			yield (p0 + p1 + q0 + q1 - (p0 + q1) * (p1 + q0)) % md


	print((sum(calc(get,upd))+n*cnt[n] - n)%md)

main()

Submission status: Runtime Error

Solution code:
import sys
def solve():
    readline = sys.stdin.readline
    N = int(readline())
    P = [list(map(int, readline().split())) for i in range(N)]

    P.sort()

    Y = [y for x, y in P]

    def compress(X):
        *XS, = set(X)
        XS.sort()
        return list(map({e: i for i, e in enumerate(XS)}.__getitem__, X))
    Y = compress(Y)

    data = [0]*(N+1)
    def add(k, x):
        while k <= N:
            data[k] += x
            k += k & -k
    def get(k):
        s = 0
        while k:
            s += data[k]
            k -= k & -k
        return s

    def gen(add, get):
        MOD = 998244353
        pow2 = [1]*N
        r = 1
        for i in range(1, N):
            pow2[i] = r = r * 2 % MOD

        for i, y in enumerate(Y):
            v1 = get(y+1); v0 = y - v1
            w1 = i - v1; w0 = (N - y - 1) - w1
            add(y+1, 1)
            p1 = pow2[v1] - 1; p0 = pow2[v0] - 1
            q1 = pow2[w1] - 1; q0 = pow2[w0] - 1
            yield (2 * ((p1+1)*(p0+1) % MOD)*((q1+1)*(q0+1) % MOD) % MOD) - (1 + p0 + p1 + q0 + q1 + p0 * (p1 + q0) + (p1 + q0) * q1) % MOD
    print(sum(gen(add, get)) % MOD)
solve()