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: Time Limit Exceeded

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()

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

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

class CombTools(object):
    def __init__(self, cap: int, mod: int):
        self.cap = cap
        self.mod = mod
        self.inv = self._calc_inv()
        self.fac = self._calc_fac()
        self.fac_inv = self._calc_fac_inv()

    def _calc_inv(self):
        inv = [0, 1]
        for i in range(2, self.cap+1):
            inv.append((self.mod - (self.mod // i) * inv[self.mod % i]) % self.mod)

        return inv

    def _calc_fac(self):
        fac = [1]
        for i in range(1, self.cap+1):
            fac.append((i * fac[-1]) % self.mod)

        return fac

    def _calc_fac_inv(self):
        fac_inv = [1]
        for i in range(1, self.cap+1):
            fac_inv.append((self.inv[i] * fac_inv[-1]) % self.mod)

        return fac_inv

    def nCr(self, n: int, r: int):
        # validation
        if r > n:
            raise ValueError("n must be larger than r (n={}, r={})".format(n, r))

        # calculation
        return self.fac[n] * self.fac_inv[n-r] * self.fac_inv[r] % self.mod


class BIT(object):
    def __init__(self, n: int):
        self.bitree = [0]*(pow(2, (n-1).bit_length()) + 1)
        self.size = len(self.bitree) - 1

    def add(self, index, value):
        while index <= self.size:
            self.bitree[index] += value
            index += (-index) & index

    def get(self, index):
        ans = 0
        while index > 0:
            ans += self.bitree[index]
            index -= (-index) & index

        return ans


# 入力
n = ni()
xs = []
ys = []
ps = []
MOD = 998244353
for _ in range(n):
    xi, yi = li()
    xs.append(xi)
    ys.append(yi)
    ps.append([xi, yi])

# 座標圧縮
xcomp = {xi: i+1 for i, xi in enumerate(sorted(xs))}
ycomp = {yi: i+1 for i, yi in enumerate(sorted(ys))}
pcomp = [[xcomp[xi], ycomp[yi]] for xi, yi in zip(xs, ys)]
pcomp.sort()

# 答え
ans = 0

# 自分が選択される
ct = CombTools(n, MOD)
for i in range(1,n+1):
    ans += i * ct.nCr(n, i)
    ans %= MOD

# BITで左右管理
leftBIT = BIT(n)
rightBIT = BIT(n)

for _, yi in pcomp:
    rightBIT.add(yi, 1)

# 左端から繰り返し
pow2 = [pow(2, i, MOD) for i in range(n+1)]
for _, yi in pcomp:
    rightBIT.add(yi, -1)

    nw = leftBIT.get(n) - leftBIT.get(yi)
    ne = rightBIT.get(n) - rightBIT.get(yi)
    sw = leftBIT.get(yi)
    se = rightBIT.get(yi)

    ans += (pow2[nw] - 1) * (pow2[se] - 1) * (pow2[ne] * pow2[sw])
    ans += (pow2[sw] - 1) * (pow2[ne] - 1) * (pow2[se] * pow2[nw])
    ans -= (pow2[nw] - 1) * (pow2[ne] - 1) * (pow2[sw] - 1) * (pow2[se] - 1)
    ans %= MOD

    leftBIT.add(yi, 1)

print(ans)

Submission status: Time Limit Exceeded

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
	ft=array.array('I', [0 for _ in range(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<=n):
			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: Time Limit Exceeded

Solution code:
import sys
import array

from operator import itemgetter

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

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


def comb(cnt,x):
	return cnt[x]-1;

def main():

	input = sys.stdin.readline
	tl=200100

	ft=[0]*tl


	md = 998244353
	n = int(input())
	xy = [[0]*2 for _ in range(n)]
	ys = []
	hp = []
	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 calc(ft,get,upd,cnt):
		for i, y in enumerate(yxi):
			v = get(ft,y+1); upd(ft,y+1)
			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(ft,get,upd,cnt))+n*cnt[n] - n)%md)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import array

from operator import itemgetter

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

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


def comb(cnt,x):
	return cnt[x]-1;

def main():

	input = sys.stdin.readline
	tl=200100

	ft=[0]*tl


	md = 998244353
	n = int(input())
	xy = [[0]*2 for _ in range(n)]
	yxi = [[0]*3 for _ in range(n)]
	ys = []
	hp = []
	for i in range(n):
		xy[i] = [int(item) for item in input().split()]
	xy.sort(key=itemgetter(0))

	for i in range(n):
		yxi[i]=[xy[i][1],xy[i][0],i]
	yxi.sort(key=itemgetter(0))

	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 calc(ft,get,upd,cnt):
		for aa in yxi:
			ix=aa[2]
			a=get(ft,ix)
			b=get(ft,n)-a
			upd(ft,ix)
			c=ix-a
			d=n-ix-1-b
		#	exc=(comb(a+b)+comb(a+c)+comb(b+d)+comb(c+d)-comb(a)-comb(b)-comb(c)-comb(d))%md
		#	cur=(comb(n)-exc)%md
		#	ans=(ans+cur)%md
		#	ans=(ans+comb(cnt,n)-comb(cnt,a+b)-comb(cnt,a+c)-comb(cnt,b+d)-comb(cnt,c+d)+comb(cnt,a)+comb(cnt,b)+comb(cnt,c)+comb(cnt,d))%md
			yield(comb(cnt,n)-comb(cnt,a+b)-comb(cnt,a+c)-comb(cnt,b+d)-comb(cnt,c+d)+comb(cnt,a)+comb(cnt,b)+comb(cnt,c)+comb(cnt,d))%md

	print((sum(calc(ft,get,upd,cnt)))%md)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import array

from operator import itemgetter

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

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


def comb(cnt,x):
	return cnt[x]-1;

def main():

	tl=200100

	ft=[0]*tl


	md = 998244353
	n = int(input())
	xy = [[0]*2 for _ in range(n)]
	yxi = [[0]*3 for _ in range(n)]
	ys = []
	hp = []
	for i in range(n):
		xy[i] = [int(item) for item in input().split()]
	xy.sort(key=itemgetter(0))

	for i in range(n):
		yxi[i]=[xy[i][1],xy[i][0],i]
	yxi.sort(key=itemgetter(0))

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

	cnt=tuple(ct)

	ans=0

	for i in range(n):
		ix=yxi[i][2]
		a=get(ft,ix)
		b=get(ft,n)-a
		c=ix-a
		d=n-ix-1-b
	#	exc=(comb(a+b)+comb(a+c)+comb(b+d)+comb(c+d)-comb(a)-comb(b)-comb(c)-comb(d))%md
	#	cur=(comb(n)-exc)%md
	#	ans=(ans+cur)%md
		ans=(ans+comb(cnt,n)-comb(cnt,a+b)-comb(cnt,a+c)-comb(cnt,b+d)-comb(cnt,c+d)+comb(cnt,a)+comb(cnt,b)+comb(cnt,c)+comb(cnt,d))%md
		upd(ft,ix)

	if(ans<0):ans+=md

	print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import array

from operator import itemgetter

input = sys.stdin.readline

tl=200100

ft=array.array('I', [0 for _ in range(tl)])

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

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

md = 998244353
n = int(input())

xyi = [[0]*3 for _ in range(n)]
for i in range(n):
	xyi[i][0],xyi[i][1] = [int(item) for item in input().split()]
xyi.sort(key=itemgetter(0))

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

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 comb(x):
	return cnt[x]-1;

ans=0

for aa in xyi:
	ix=aa[2]
	a=get(ix)
	b=get(n)-a
	c=ix-a
	d=n-ix-1-b
#	exc=(comb(a+b)+comb(a+c)+comb(b+d)+comb(c+d)-comb(a)-comb(b)-comb(c)-comb(d))%md
#	cur=(comb(n)-exc)%md
#	ans=(ans+cur)%md
	ans=(ans+comb(n)-comb(a+b)-comb(a+c)-comb(b+d)-comb(c+d)+comb(a)+comb(b)+comb(c)+comb(d))%md
	upd(ix)

if(ans<0):ans+=md

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import array

from operator import itemgetter

input = sys.stdin.readline

tl=200100

ft=array.array('I', [0 for _ in range(tl)])

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

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

md = 998244353
n = int(input())

xyi = [[0]*3 for _ in range(n)]
for i in range(n):
	xyi[i][0],xyi[i][1] = [int(item) for item in input().split()]
xyi.sort(key=itemgetter(0))

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

cnt=array.array('I', [0 for _ in range(n+1)])

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

def comb(x):
	return cnt[x]-1;

ans=0

for aa in xyi:
	ix=aa[2]
	a=get(ix)
	b=get(n)-get(ix)
	c=ix-a
	d=n-ix-1-b
	exc=(comb(a+b)+comb(a+c)+comb(b+d)+comb(c+d)-comb(a)-comb(b)-comb(c)-comb(d))%md
	cur=(comb(n)-exc)%md
	ans=(ans+cur)%md
	upd(ix)

if(ans<0):ans+=md

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys
from operator import itemgetter

input = sys.stdin.readline

tl=200100

ft=np.zeros(tl,dtype=int)

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

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

md = 998244353
n = int(input())

xyi = [[0]*3 for _ in range(n)]
for i in range(n):
	xyi[i][0],xyi[i][1] = [int(item) for item in input().split()]
xyi.sort(key=itemgetter(0))

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

cnt=np.zeros(n+1,dtype=int)

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

def comb(x):
	return cnt[x]-1;

ans=0

for aa in xyi:
	ix=aa[2]
	a=get(ix)
	b=get(n)-get(ix)
	c=ix-a
	d=n-ix-1-b
	exc=(comb(a+b)+comb(a+c)+comb(b+d)+comb(c+d)-comb(a)-comb(b)-comb(c)-comb(d))%md
	cur=(comb(n)-exc)%md
	ans=(ans+cur)%md
	upd(ix)

if(ans<0):ans+=md

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from operator import itemgetter

input = sys.stdin.readline

tl=200100

ft=[0]*tl

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

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

md = 998244353
n = int(input())

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

for i in range(n):
	yi[i]=[xy[i][1],i]
yi.sort(key=itemgetter(0))

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

def comb(x):
	return cnt[x]-1;

ans=0

for aa in yi:
	ix=aa[1]
	a=get(ix)
	b=get(n)-get(ix)
	c=ix-a
	d=n-ix-1-b
	exc=(comb(a+b)+comb(a+c)+comb(b+d)+comb(c+d)-comb(a)-comb(b)-comb(c)-comb(d))%md
	cur=(comb(n)-exc)%md
	ans=(ans+cur)%md
	upd(ix)

if(ans<0):ans+=md

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
def solve():
    readline = sys.stdin.readline
    write = sys.stdout.write
    MOD = 998244353

    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):
        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]; p0 = pow2[v0]
            q1 = pow2[w1]; q0 = pow2[w0]
            yield (pow(2, 1+v0+v1+w0+w1, MOD) - (1 - p0 - p1 - q0 - q1 + (p0 + q1) * (p1 + q0))) % MOD
    write("%d\n" % (sum(gen(add, get)) % MOD))
solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
def solve():
    readline = sys.stdin.readline
    write = sys.stdout.write
    MOD = 998244353

    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):
        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]; p0 = pow2[v0]
            q1 = pow2[w1]; q0 = pow2[w0]
            yield (2 * (p1*p0 % MOD)*(q1*q0 % MOD) % MOD) - (1 - p0 - p1 - q0 - q1 + (p0 + q1) * (p1 + q0)) % MOD
    write("%d\n" % (sum(gen(add, get)) % MOD))
solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    N = int(input())
    P = [list(map(int, input().split())) for i in range(N)]
    MOD = 998244353

    P.sort()

    Y = [y for x, y in P]

    def compress(X):
        *XS, = set(X)
        XS.sort()
        return {e: i for i, e in enumerate(XS)}
    MY = 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

    pow2 = [1]*N
    r = 1
    for i in range(1, N):
        pow2[i] = r = r * 2 % MOD

    ans = 0
    for i, y in enumerate(Y):
        y = MY[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
        ans += 2 * ((p1+1)*(p0+1) % MOD)*((q1+1)*(q0+1) % MOD) % MOD
        ans -= (1 + p0 + p1 + q0 + q1 + p0 * (p1 + q0) + (p1 + q0) * q1) % MOD
    print(ans % MOD)
solve()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = [list(map(int, input().split())) for i in range(N)]
MOD = 998244353

P.sort()

def compress(P, d):
    *XS, = {s[d] for s in P}
    XS.sort()
    return {e: i for i, e in enumerate(XS)}
MX = compress(P, 0)
MY = compress(P, 1)

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

ans = 0
for i in range(N):
    x, y = P[i]
    x = MX[x]; y = MY[y]
    v1 = get(y+1); v0 = y - v1
    w1 = i - v1; w0 = (N - y - 1) - w1
    add(y+1, 1)
    p1 = pow(2, v1, MOD)-1
    p0 = pow(2, v0, MOD)-1
    q1 = pow(2, w1, MOD)-1
    q0 = pow(2, w0, MOD)-1
    ans += 2 * ((p1+1)*(p0+1) % MOD)*((q1+1)*(q0+1) % MOD) % MOD
    ans -= (1 + p0 + p1 + q0 + q1 + p0 * (p1 + q0) + (p1 + q0) * q1) % MOD
print(ans % MOD)

Submission status: Time Limit Exceeded

Solution code:
tl=200100

ft=[0]*tl

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

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

md = 998244353
n = int(input())
cy = [[0] * 4 for _ in range(n)]
xy = [[0]*2 for _ in range(n)]
yxi = [[0]*3 for _ in range(n)]
ys = []
hp = []
for i in range(n):
	xy[i] = [int(item) for item in input().split()]
xy.sort()

for i in range(n):
	yxi[i]=[xy[i][1],xy[i][0],i]
yxi.sort()

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

def comb(x):
	return cnt[x]-1;

ans=0

for i in range(n):
	ix=yxi[i][2]
	a=get(ix)
	b=get(n)-get(ix)
	c=ix-a
	d=n-ix-1-b
	exc=(comb(a+b)+comb(a+c)+comb(b+d)+comb(c+d)-comb(a)-comb(b)-comb(c)-comb(d))%md
	cur=(comb(n)-exc)%md
	ans=(ans+cur)%md
	upd(ix)

if(ans<0):ans+=md

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#Modified from #6728952
from bisect import *
from heapq import *
 
md = 998244353
n = int(input())
hp = []
for _ in range(n):
    heappush(hp, list(map(int, input().split())))
cy = [[0] * 4 for _ in range(n)]
xy = []
ys = []

cnt=[0]*n

for i in range(n):
	cnt[i]=pow(2,i,md)

for i in range(n):
    x, y = heappop(hp)
    s = bisect(ys, y)
#    cy[i][3] = pow(2, s, md)
#    cy[i][2] = pow(2, i - s, md)
    cy[i][3] = cnt[s]
    cy[i][2] = cnt[i - s]
    ys.insert(s, y)
    xy.append([x, y])
ys = []
for i in range(n - 1, -1, -1):
    x, y = xy[i]
    s = bisect(ys, y)
#    cy[i][0] = pow(2, s, md)
#    cy[i][1] = pow(2, n - 1 - i - s, md)
    cy[i][0] = cnt[s]
    cy[i][1] = cnt[n - 1 - i - s]
    ys.insert(s, y)
#ans = pow(2, n - 1, md) * n % md
ans = cnt[n - 1]* n % md
for i in range(n):
    c0, c1, c2, c3 = cy[i]
#    ans = (ans + (c0 - 1) * (c2 - 1) * c1 * c3 + (c1 - 1) * (c3 - 1) * c0 * c2
#           - (c0 - 1) * (c1 - 1) * (c2 - 1) * (c3 - 1)) % md
    ans = (ans + (c0 - 1) * (c2 - 1) * c1 * c3 + (c1 - 1) * (c3 - 1) * c0 * c2
           - (c0 - 1) * (c1 - 1) * (c2 - 1) * (c3 - 1)) % md
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
from math import ceil, log


class SegmentTree:
    def __init__(self, length, init_value=None, aggfunc=min):
        self.init_value = init_value
        self.aggfunc = aggfunc

        self.data = [init_value] * (2 ** (1 + ceil(log(length, 2))) - 1)
        self.origin = len(self.data) // 2

    def update(self, idx, value):
        i = idx + self.origin
        self.data[i] = value
        while i > 0:
            i = (i - 1) // 2
            new_value = self.aggfunc((self.data[i * 2 + 1], self.data[i * 2 + 2]))
            if self.data[i] != new_value:
                self.data[i] = new_value
            else:
                break

    def query(self, start, stop):
        return self._query(start, stop, 0, 0, self.origin + 1)

    def _query(self, start, stop, k, l, r):
        if (start <= l) & (r <= stop):
            return self.data[k]
        elif (r <= start) | (stop <= l):
            return self.init_value
        else:
            return self.aggfunc(
                (
                    self._query(start, stop, k * 2 + 1, l, (l + r) // 2),
                    self._query(start, stop, k * 2 + 2, (l + r) // 2, r),
                )
            )


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

xy.sort()

xs = [x for x, y in xy]
ys = [y for x, y in xy]

ys.sort()
x_dict = dict(zip(xs, range(n)))
y_dict = dict(zip(ys, range(n)))

pow2 = [1]
for _ in range(1, n):
    pow2.append(pow2[-1] * 2 % mod)

segment_tree = SegmentTree(n, 0, sum)
ans = 0
for x, y in xy:
    x, y = x_dict[x], y_dict[y]
    n0 = segment_tree.query(0, y)
    n1 = x - n0
    n2 = y - n0
    n3 = n - n0 - n1 - n2 - 1

    segment_tree.update(y, 1)

    counts = [n0, n1, n2, n3]
    for exist in product([False, True], repeat=4):
        tmp = 1
        for e, c in zip(exist, counts):
            if e:
                tmp *= pow2[c] - 1
        if (exist[1] & exist[2]) | (exist[0] & exist[3]):
            tmp *= 2
        ans += tmp
ans %= mod

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
from math import ceil, log2


class SegmentTree:
    def __init__(self, length, init_value=None, aggfunc=min):
        self.init_value = init_value
        self.aggfunc = aggfunc

        depth = ceil(log2(length))
        self.data = [init_value] * (2 ** (1 + depth) - 1)
        self.origin = 2 ** depth - 1

    def update(self, idx, value):
        i = idx + self.origin
        self.data[i] = value
        while i > 0:
            i = (i - 1) // 2
            new_value = self.aggfunc((self.data[i * 2 + 1], self.data[i * 2 + 2]))
            if self.data[i] != new_value:
                self.data[i] = new_value
            else:
                break

    def query(self, start, stop):
        return self._query(start, stop, 0, 0, self.origin + 1)

    def _query(self, start, stop, k, l, r):
        if (start <= l) & (r <= stop):
            return self.data[k]
        elif (r <= start) | (stop <= l):
            return self.init_value
        else:
            return self.aggfunc(
                (
                    self._query(start, stop, k * 2 + 1, l, (l + r) // 2),
                    self._query(start, stop, k * 2 + 2, (l + r) // 2, r),
                )
            )


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

xy.sort()

xs = [x for x, y in xy]
ys = [y for x, y in xy]

ys.sort()
x_dict = dict(zip(xs, range(n)))
y_dict = dict(zip(ys, range(n)))

pow2 = [None] * n
pow2[0] = 1
for i in range(1, n):
    pow2[i] = pow2[i - 1] * 2 % mod

segment_tree = SegmentTree(n, 0, sum)
ans = 0
for x, y in xy:
    x, y = x_dict[x], y_dict[y]
    n0 = segment_tree.query(0, y)
    n1 = x - n0
    n2 = y - n0
    n3 = n - n0 - n1 - n2 - 1

    segment_tree.update(y, 1)

    counts = [n0, n1, n2, n3]
    for exist in product([False, True], repeat=4):
        tmp = 1
        for e, c in zip(exist, counts):
            if e:
                tmp *= pow2[c] - 1
        if (exist[1] & exist[2]) | (exist[0] & exist[3]):
            tmp *= 2
        ans += tmp
ans %= mod

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
from math import ceil, log2


class SegmentTree:
    def __init__(self, length, init_value=None, aggfunc=min):
        self.length = length
        self.init_value = init_value
        self.aggfunc = aggfunc
        self.depth = ceil(log2(length))
        self.data = [init_value] * (2 ** (1 + self.depth) - 1)
        self.origin = 2 ** self.depth - 1

    def update(self, idx, value):
        i = idx + self.origin
        self.data[i] = value
        while i > 0:
            i = (i - 1) // 2
            new_value = self.aggfunc((self.data[i * 2 + 1], self.data[i * 2 + 2]))
            if self.data[i] != new_value:
                self.data[i] = new_value
            else:
                break

    def query(self, start, stop):
        return self._query(start, stop, 0, 0, 2 ** self.depth)

    def _query(self, start, stop, k, l, r):
        if (start <= l) & (r <= stop):
            return self.data[k]
        elif (r <= start) | (stop <= l):
            return self.init_value
        else:
            return self.aggfunc(
                (
                    self._query(start, stop, k * 2 + 1, l, (l + r) // 2),
                    self._query(start, stop, k * 2 + 2, (l + r) // 2, r),
                )
            )


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

xy.sort()

xs = [x for x, y in xy]
ys = [y for x, y in xy]

ys.sort()
x_dict = dict(zip(xs, range(n)))
y_dict = dict(zip(ys, range(n)))

points = [(x_dict[x], y_dict[y]) for x, y in xy]

segment_tree = SegmentTree(n, 0, sum)

ans = 0
for x, y in points:

    n0 = segment_tree.query(0, y)
    n1 = x - n0
    n2 = y - n0
    n3 = n - n0 - n1 - n2 - 1

    segment_tree.update(y, 1)

    counts = [n0, n1, n2, n3]
    for exist in product([False, True], repeat=4):
        tmp = 1
        for e, c in zip(exist, counts):
            if e:
                tmp *= (2 ** c) % mod - 1
        if (exist[1] & exist[2]) | (exist[0] & exist[3]):
            tmp *= 2
        ans += tmp
ans %= mod

print(ans)

Submission status: Time Limit Exceeded

Solution code:

import sys
import math
from operator import itemgetter, attrgetter

INF = 1 << 20
MOD = 998244353
# 座標
class Pair:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def main():
    N = int(sys.stdin.readline().strip())
    numbers = []
    for i in range(N):
        x, y = [int(i) for i in sys.stdin.readline().strip().split()]
        numbers.append(Pair(x, y))

    print("%d" % solve(N, numbers))

    
def solve(N, numbers):
    ans = 0
    

    # sort based Y
    numbers.sort(key=attrgetter("y"))
    for index in range(N):
        numbers[index].y = index

    # compressed numbers
    # sort based X
    numbers.sort(key=attrgetter("x"))
    for index in range(N):
        numbers[index].x = index
             
    # 各象限に存在する点の個数
    a = [0 for i in range(N)]
    b = [0 for i in range(N)]
    c = [0 for i in range(N)]
    d = [0 for i in range(N)]

    # 一番左の点から数えていく
    for rep in range(2):
        # treeを構築。これは、あるy座標以下の点の数がどれだけあるかを数えるもの
        bit = BIT(N)
        # 都合上、iは「それまでに追加した、今計算の対象となっている座標よりも左にある点の数」になる。
        for i in range(N):
            # 左から考えるので、その点より下にある点の数を代入
            a[i] = bit.sum(numbers[i].y)

            # これまでに追加した点の数マイナス、自分より下にある点の数(a)を引く
            b[i] = i - a[i]

            # 点を足す
            bit.update(numbers[i].y)
        numbers.reverse()
        a,b,c,d = c,d,a,b
        a.reverse()
        b.reverse()
        c.reverse()
        d.reverse()

    for i in range(N):
        ans += f([a[i], b[i], c[i], d[i]])
    ans %= MOD
    return ans



def f(nums):
    res = 0
    
    o = [2**i-1 for i in nums]
    ox = [i+1 for i in o]
    res += (ox[0] * o[1] * o[2] * ox[3])
    res += (o[0] * ox[1] * ox[2] * o[3])
    res += (ox[0] * ox[1] * ox[2] * ox[3])
    res -= (o[0] * o[1] * o[2] * o[3])

    return res



# Binary Indexed Tree
# Reference http://hos.ac/slides/20140319_bit.pdf
class BIT:
    def __init__(self, size):
        self.bits = [0 for i in range(size+1)]
        self.size = size


    def update(self, index, value = 1):
        index += 1
        while index <= self.size:
            self.bits[index] += value
            index += index & (-1 * index)
    
    def sum(self, index):
        index += 1
        ans = 0
        while index > 0:
            ans += self.bits[index]
            index -= index & (-1 * index)
        return ans

if __name__ == "__main__":
    main()