Connected Components (Codeforces 292D)
Tags: DP, dsu

We already know of the large corporation where Polycarpus works as a system administrator. The computer network there consists of n computers and m cables that connect some pairs of computers. In other words, the computer network can be represented as some non-directed graph with n nodes and m edges. Let's index the computers with integers from 1 to n, let's index the cables with integers from 1 to m.Polycarpus was given an important task — check the reliability of his company's network. For that Polycarpus decided to carry out a series of k experiments on the computer network, where the i-th experiment goes as follows:  Temporarily disconnect the cables with indexes from li to ri, inclusive (the other cables remain connected).  Count the number of connected components in the graph that is defining the computer network at that moment.  Re-connect the disconnected cables with indexes from li to ri (that is, restore the initial network). Help Polycarpus carry out all experiments and for each print the number of connected components in the graph that defines the computer network through the given experiment. Isolated vertex should be counted as single component.

Input: The first line contains two space-separated integers n, m (2 ≤ n ≤ 500; 1 ≤ m ≤ 104) — the number of computers and the number of cables, correspondingly.The following m lines contain the cables' description. The i-th line contains space-separated pair of integers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the numbers of the computers that are connected by the i-th cable. Note that a pair of computers can be connected by multiple cables.The next line contains integer k (1 ≤ k ≤ 2·104) — the number of experiments. Next k lines contain the experiments' descriptions. The i-th line contains space-separated integers li, ri (1 ≤ li ≤ ri ≤ m) — the numbers of the cables that Polycarpus disconnects during the i-th experiment. 

Output: Print k numbers, the i-th number represents the number of connected components of the graph that defines the computer network during the i-th experiment. 


Sample Inputs:
6 5
1 2
5 4
2 3
3 1
3 6
6
1 3
2 5
1 5
5 5
2 4
3 3

Sample Outputs:
4
5
6
3
4
2

Solution (Python):
import os, sys
from io import BytesIO, IOBase
from copy import copy

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')

class disjointset:

    def __init__(self, n):
        (self.rank, self.parent, self.n) = ([0] * (n + 1), [i for i in range(n + 1)], n)

    def find(self, x):
        xcopy = x
        while x != self.parent[x]:
            x = self.parent[x]
        while xcopy != x:
            (self.parent[xcopy], xcopy) = (x, self.parent[xcopy])
        return x

    def union(self, x, y):
        (xpar, ypar) = (self.find(x), self.find(y))
        if xpar == ypar:
            return
        (par, child) = (xpar, ypar)
        if self.rank[xpar] < self.rank[ypar]:
            (par, child) = (ypar, xpar)
        elif self.rank[xpar] == self.rank[ypar]:
            self.rank[xpar] += 1
        self.parent[child] = par
        self.n -= 1
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
inp_enu = lambda dtype: [(i, x) for (i, x) in enumerate(inp(dtype))]
inp_enus = lambda dtype, n: [[i] + inp(dtype) for i in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
(n, m) = inp(int)
(dis, edges) = (disjointset(n), inp_2ds(int, m))
(pre, suf) = ([(copy(dis.parent), copy(dis.rank), dis.n)], [copy(dis.parent)])
for (u, v) in edges:
    dis.union(u, v)
    pre.append((copy(dis.parent), copy(dis.rank), dis.n))
dis1 = disjointset(n)
for (u, v) in edges[::-1]:
    dis1.union(u, v)
    suf.append(copy(dis1.parent))
suf.reverse()
for _ in range(int(input())):
    (l, r) = inp(int)
    (dis.parent, dis.rank, dis.n) = (copy(pre[l - 1][0]), copy(pre[l - 1][1]), pre[l - 1][2])
    dis1.parent = copy(suf[r])
    for i in range(1, n + 1):
        dis.union(dis.parent[i], dis1.parent[i])
    print(dis.n)

Solution (Python):
import os, sys, collections, heapq, itertools, functools
if os.path.exists('in.txt'):
    file = open('in.txt')
    input = file.readline
else:
    input = sys.stdin.readline
from functools import reduce, lru_cache
from itertools import accumulate, chain, combinations, count
from itertools import groupby, permutations, product, zip_longest
from heapq import heapify, heappush, heappop, heapreplace, merge, nlargest, nsmallest
from collections import Counter, defaultdict, deque
from bisect import bisect_left, bisect_right
from math import comb, floor, ceil, inf, gcd, sqrt, atan2
import operator
from copy import copy
readi = lambda : int(input())
readis = lambda : list(map(int, input().split()))
reads = lambda : input().rstrip()
readss = lambda : input().split()

class UF:

    def __init__(self, n, cp=None):
        if cp:
            self.Fa = cp.Fa[:]
        else:
            self.Fa = [n] + [-1] * n

    def getroot(self, i):
        root = i
        while self.Fa[root] >= 0:
            root = self.Fa[root]
        while i != root:
            (tmp, self.Fa[i]) = (self.Fa[i], root)
            i = tmp
        return root

    def union(self, a, b):
        (ra, rb) = (self.getroot(a), self.getroot(b))
        if ra != rb:
            self.Fa[0] -= 1
            self.Fa[rb] += self.Fa[ra]
            self.Fa[ra] = rb
            return True
        return False

def solution():
    (n, m) = readis()
    edges = [[0, 0]] + [readis() for _ in range(m)]
    uf = UF(n)
    Rused = [r for r in range(m, 0, -1) if uf.union(*edges[r])][::-1] + [m + 1]
    k = len(Rused)
    Lused = [0]
    F = [list(range(n - k + 1, n + 1))]
    uf = UF(n)
    for l in range(1, m + 1):
        if uf.union(*edges[l]):
            Lused.append(l)
            f = [1] * k
            f[-1] = uf.Fa[0]
            tmp = UF(n, uf)
            for ri in range(k - 2, -1, -1):
                if Rused[ri] <= l:
                    break
                tmp.union(*edges[Rused[ri]])
                f[ri] = tmp.Fa[0]
            F.append(f)
    Rnex = [0] * (m + 1)
    for j in range(1, k):
        Rnex[Rused[j - 1]:Rused[j]] = [j] * (Rused[j] - Rused[j - 1])
    Lnex = [k - 1] * (m + 1)
    for j in range(k - 1):
        Lnex[Lused[j] + 1:Lused[j + 1] + 1] = [j] * (Lused[j + 1] - Lused[j])
    res = []
    for _ in range(readi()):
        (l, r) = readis()
        res.append(F[Lnex[l]][Rnex[r]])
    print(*res, sep='\n')
for i in range(1):
    solution()

Solution (Python):
import os, sys, collections, heapq, itertools, functools
if os.path.exists('in.txt'):
    file = open('in.txt')
    input = file.readline
else:
    input = sys.stdin.readline
from functools import reduce, lru_cache
from itertools import accumulate, chain, combinations, count
from itertools import groupby, permutations, product, zip_longest
from heapq import heapify, heappush, heappop, heapreplace, merge, nlargest, nsmallest
from collections import Counter, defaultdict, deque
from bisect import bisect_left, bisect_right
from math import comb, floor, ceil, inf, gcd, sqrt, atan2
import operator
from copy import copy
readi = lambda : int(input())
readis = lambda : list(map(int, input().split()))
reads = lambda : input().rstrip()
readss = lambda : input().split()

class UF:

    def __init__(self, n, cp=None):
        if cp:
            self.Fa = cp.Fa[:]
        else:
            self.Fa = [n] + [-1] * n

    def getroot(self, i):
        root = i
        while self.Fa[root] >= 0:
            root = self.Fa[root]
        while i != root:
            tmp = self.Fa[i]
            self.Fa[i] = root
            i = tmp
        return root

    def union(self, a, b):
        (ra, rb) = (self.getroot(a), self.getroot(b))
        if ra != rb:
            self.Fa[0] -= 1
            self.Fa[rb] += self.Fa[ra]
            self.Fa[ra] = rb
            return True
        return False

def solution():
    (n, m) = readis()
    edges = [[0, 0]] + [readis() for _ in range(m)]
    uf = UF(n)
    Rused = [r for r in range(m, 0, -1) if uf.union(*edges[r])][::-1] + [m + 1]
    k = len(Rused)
    Lused = [0]
    F = [list(range(n - k + 1, n + 1))]
    uf = UF(n)
    for l in range(1, m + 1):
        if uf.union(*edges[l]):
            Lused.append(l)
            f = [1] * k
            f[-1] = uf.Fa[0]
            tmp = UF(n, uf)
            for ri in range(k - 2, -1, -1):
                if Rused[ri] <= l:
                    break
                tmp.union(*edges[Rused[ri]])
                f[ri] = tmp.Fa[0]
            F.append(f)
    Rnex = [0] * (m + 1)
    for j in range(1, k):
        Rnex[Rused[j - 1]:Rused[j]] = [j] * (Rused[j] - Rused[j - 1])
    Lnex = [k - 1] * (m + 1)
    for j in range(k - 1):
        Lnex[Lused[j]:Lused[j + 1]] = [j] * (Lused[j + 1] - Lused[j])
    Rnex = [bisect_right(Rused, i) for i in range(m + 1)]
    Lnex = [bisect_left(Lused, i) - 1 for i in range(m + 1)]
    Q = [readis() for _ in range(readi())]
    print(*[F[Lnex[l]][Rnex[r]] for (l, r) in Q], sep='\n')
for i in range(1):
    solution()