Vika and Segments (Codeforces 610D)
Tags: Others, two pointers

Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column.Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.

Input: The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of segments drawn by Vika.Each of the next n lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1, y1, x2, y2 ≤ 109) — the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.

Output: Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.

Note: In the first sample Vika will paint squares (0, 1), (1, 1), (2, 1), (1, 2), (1, 3), (1, 4), (0, 3) and (2, 3).

Sample Inputs:
3
0 1 2 1
1 4 1 2
0 3 2 3

4
-2 -1 2 -1
2 1 -2 1
-1 -2 -1 2
1 2 1 -2

Sample Outputs:
8

16

Solution (Python):
from sys import stdin
from itertools import repeat
from collections import defaultdict

def main():
    n = int(stdin.readline())
    h = defaultdict(list)
    w = defaultdict(list)
    for i in range(n):
        (a, b, c, d) = map(int, input().split())
        if a > c:
            (a, c) = (c, a)
        if b > d:
            (b, d) = (d, b)
        if a == c:
            h[a].append((b, d))
        else:
            w[b].append((a, c))
    ans = 0
    ys = set()
    es = defaultdict(list)
    qs = defaultdict(list)
    for (t, l) in h.items():
        l.sort()
        l.append((1001001001, 1001001001))
        nl = []
        p = r = l[0][0]
        for (a, b) in l:
            if a > r:
                nl.append((p, r))
                ans += r - p + 1
                es[p].append((1, t))
                es[r + 1].append((-1, t))
                p = r = a
            if r < b:
                r = b
        l = nl
        ys.add(t)
    for (t, l) in w.items():
        l.sort()
        l.append((1001001001, 1001001001))
        nl = []
        p = r = l[0][0]
        for (a, b) in l:
            if a > r:
                nl.append((p, r))
                ys.add(p)
                ys.add(r)
                es[t].append((2, p, r))
                ans += r - p + 1
                p = r = a
            if r < b:
                r = b
        l = nl
    ys = [-1001001001] + list(ys)
    ys.sort()
    d = {v: i for (i, v) in enumerate(ys)}
    l = len(ys)
    bs = [0] * l
    for x in sorted(es.keys()):
        for q in sorted(es[x]):
            if q[0] <= 1:
                (a, b) = (q[0], d[q[1]])
                while b < l:
                    bs[b] += a
                    b += b - (b & b - 1)
            else:
                (a, b) = (d[q[1]] - 1, d[q[2]])
                while b > 0:
                    ans -= bs[b]
                    b = b & b - 1
                while a > 0:
                    ans += bs[a]
                    a = a & a - 1
    print(ans)
main()

Solution (Python):
from sys import stdin
from itertools import repeat
from collections import defaultdict

def main():
    n = int(stdin.readline())
    h = defaultdict(list)
    w = defaultdict(list)
    for i in range(n):
        (a, b, c, d) = map(int, input().split())
        if a > c:
            (a, c) = (c, a)
        if b > d:
            (b, d) = (d, b)
        if a == c:
            h[a].append((b, d))
        else:
            w[b].append((a, c))
    ans = 0
    ys = set()
    es = defaultdict(list)
    qs = defaultdict(list)
    for (t, l) in h.items():
        l.sort()
        l.append((1001001001, 1001001001))
        nl = []
        p = r = l[0][0]
        for (a, b) in l:
            if a > r:
                nl.append((p, r))
                ans += r - p + 1
                es[p].append((1, t))
                es[r + 1].append((-1, t))
                p = r = a
            if r < b:
                r = b
        l = nl
        ys.add(t)
    for (t, l) in w.items():
        l.sort()
        l.append((1001001001, 1001001001))
        nl = []
        p = r = l[0][0]
        for (a, b) in l:
            if a > r:
                nl.append((p, r))
                ys.add(p)
                ys.add(r)
                es[t].append((2, p, r))
                ans += r - p + 1
                p = r = a
            if r < b:
                r = b
        l = nl
    ys = [-1001001001] + list(ys)
    ys.sort()
    d = {v: i for (i, v) in enumerate(ys)}
    l = len(ys)
    bs = [0] * l
    for x in sorted(es.keys()):
        for q in sorted(es[x]):
            if q[0] <= 1:
                (a, b) = (q[0], d[q[1]])
                while b < l:
                    bs[b] += a
                    b += b - (b & b - 1)
            else:
                (a, b) = (d[q[1]] - 1, d[q[2]])
                while b > 0:
                    ans -= bs[b]
                    b = b & b - 1
                while a > 0:
                    ans += bs[a]
                    a = a & a - 1
    print(ans)
main()

Solution (Python):
from collections import defaultdict
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def fenwick_tree(n):
    tree = [0] * (n + 1)
    return tree

def get_sum0(i):
    s = 0
    while i > 0:
        s += tree[i]
        i -= i & -i
    return s

def get_sum(s, t):
    ans = 0 if s > t else get_sum0(t) - get_sum0(s - 1)
    return ans

def add(i, x):
    while i < len(tree):
        tree[i] += x
        i += i & -i
n = int(input())
(d1, d2) = (defaultdict(lambda : []), defaultdict(lambda : []))
for _ in range(n):
    (x1, y1, x2, y2) = map(int, input().split())
    if x1 > x2:
        (x1, x2) = (x2, x1)
    if y1 > y2:
        (y1, y2) = (y2, y1)
    if y1 == y2:
        d1[y1].append((x1, x2))
    else:
        d2[x1].append((y1, y2))
ans = 0
z = []
(x0, y0) = (set(), set())
for y in d1:
    u = d1[y]
    u.sort()
    (l, r) = u[0]
    for (l0, r0) in u:
        if r < l0:
            ans += r - l + 1
            z.append((l, y, r, y))
            l = l0
        r = max(r, r0)
    ans += r - l + 1
    z.append((l, y, r, y))
for x in d2:
    u = d2[x]
    u.sort()
    (l, r) = u[0]
    for (l0, r0) in u:
        if r < l0:
            ans += r - l + 1
            z.append((x, l, x, r))
            l = l0
        r = max(r, r0)
    ans += r - l + 1
    z.append((x, l, x, r))
for (x1, y1, x2, y2) in z:
    x0.add(x1)
    x0.add(x2)
    y0.add(y1)
    y0.add(y2)
(x0, y0) = (list(x0), list(y0))
x0.sort()
y0.sort()
(d1, d2) = (dict(), dict())
(m, l) = (len(x0), len(y0))
for i in range(m):
    d1[x0[i]] = i + 1
for i in range(l):
    d2[y0[i]] = i + 1
u = [[] for _ in range(m + 2)]
v = [[] for _ in range(m + 2)]
for (x3, y3, x4, y4) in z:
    (x1, y1, x2, y2) = (d1[x3], d2[y3], d1[x4], d2[y4])
    if y1 == y2:
        u[x1].append((y1, 1))
        u[x2 + 1].append((y1, -1))
    else:
        v[x1].append((y1, y2))
tree = fenwick_tree(l + 5)
ng = 0
for i in range(1, m + 1):
    for (j, c) in u[i]:
        add(j, c)
    for (l0, r0) in v[i]:
        ng += get_sum(l0, r0)
ans -= ng
print(ans)