human
Write me a Python program to print the number of pieces the square is divided into after drawing all the segments given the following:
Solve in Python:
There is a square of size $10^6 \times 10^6$ on the coordinate plane with four points $(0, 0)$, $(0, 10^6)$, $(10^6, 0)$, and $(10^6, 10^6)$ as its vertices.

You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.

Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.

-----Input-----

The first line contains two integers $n$ and $m$ ($0 \le n, m \le 10^5$) — the number of horizontal segments and the number of vertical segments.

The next $n$ lines contain descriptions of the horizontal segments. The $i$-th line contains three integers $y_i$, $lx_i$ and $rx_i$ ($0 < y_i < 10^6$.
$0 \le lx_i < rx_i \le 10^6$), which means the segment connects $(lx_i, y_i)$ and $(rx_i, y_i)$.

The next $m$ lines contain descriptions of the vertical segments. The $i$-th line contains three integers $x_i$, $ly_i$ and $ry_i$ ($0 < x_i < 10^6$.
$0 \le ly_i < ry_i \le 10^6$), which means the segment connects $(x_i, ly_i)$ and $(x_i, ry_i)$.

It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.

-----Output-----

Print the number of pieces the square is divided into after drawing all the segments.

-----Example-----
Input
3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000

Output
7

-----Note-----

 The sample is like this: [Image]
assistant
#Here is Python program to print the number of pieces the square is divided into after drawing all the segments.

import sys
input=sys.stdin.readline

class BIT:
  def __init__(self,n):self.n=n+1;self.BIT=[0]*self.n
  def add(self,i,x):
    idx=i
    while idx<self.n:self.BIT[idx]+=x;idx+=(idx&-idx)
  def _sum(self,i):
    if i==-1:return -1
    ret=0;idx=i
    while idx>0:ret+=self.BIT[idx];idx-=(idx&-idx)
    return ret
  def sum(self,l,r):return self._sum(r)-self._sum(l-1)
  def value(self,i):return self._sum(i)-self._sum(i-1)

bound=10**6
n,m=map(int,input().split())
yoko_edges=[list(map(int,input().split())) for _ in range(n)]
yoko_edges=sorted(yoko_edges,reverse=True,key=lambda x:x[0])
ue_tate_edges=[[] for _ in range(bound+1)]
sita_tate_edges=[[] for _ in range(bound+1)]
tate_edges=BIT(bound)
tate_edges.add(bound,1)
ans=1
for _ in range(m):
    x,l,r=map(int,input().split())
    if l==0 and r==bound:tate_edges.add(x,1);ans+=1
    elif l==0:sita_tate_edges[r].append(x)
    elif r==bound:ue_tate_edges[l].append(x);tate_edges.add(x,1)
prev=bound-1
for y,l,r in yoko_edges:
    while prev>=y:
        for x in sita_tate_edges[prev]:tate_edges.add(x,1)
        for x in ue_tate_edges[prev+1]:tate_edges.add(x,-1)
        prev-=1
    ans+=tate_edges.sum(l,r)-1
print(ans)