Anton and Permutation (Codeforces 785E)
Tags: Others, data structures

Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≤ i < j ≤ n and ai > aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≤ i ≤ n.

Input: The first line of the input contains two integers n and q (1 ≤ n ≤ 200 000, 1 ≤ q ≤ 50 000) — the length of the permutation and the number of operations that Anton does.Each of the following q lines of the input contains two integers li and ri (1 ≤ li, ri ≤ n) — the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.

Output: Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.

Note: Consider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.

Sample Inputs:
5 4
4 5
2 4
2 5
2 2

2 1
2 1

6 7
1 4
3 5
2 3
3 3
3 6
2 1
5 1

Sample Outputs:
1
4
3
3

1

5
6
7
7
10
11
8

Solution (Python):
import sys
import math
import bisect
from heapq import heapify, heappop, heappush
from collections import deque, defaultdict, Counter
from functools import lru_cache
from itertools import accumulate, combinations, permutations
MOD = 10 ** 9 + 7
MOD99 = 998244353
input = lambda : sys.stdin.readline().strip()
NI = lambda : int(input())
NMI = lambda : map(int, input().split())
NLI = lambda : list(NMI())
SI = lambda : input()
SMI = lambda : input().split()
SLI = lambda : list(SMI())
EI = lambda m: [NLI() for _ in range(m)]
import math
from bisect import bisect_left, bisect_right, insort
from typing import Generic, Iterable, Iterator, TypeVar, Union, List
T = TypeVar('T')

class SortedMultiset(Generic[T]):
    BUCKET_RATIO = 50
    REBUILD_RATIO = 170

    def _build(self, a=None) -> None:
        """"""
        if a is None:
            a = list(self)
        size = self.size = len(a)
        bucket_size = int(math.ceil(math.sqrt(size / self.BUCKET_RATIO)))
        self.a = [a[size * i // bucket_size:size * (i + 1) // bucket_size] for i in range(bucket_size)]

    def __init__(self, a: Iterable[T]=[]) -> None:
        """"""
        a = list(a)
        if not all((a[i] <= a[i + 1] for i in range(len(a) - 1))):
            a = sorted(a)
        self._build(a)

    def __iter__(self) -> Iterator[T]:
        for i in self.a:
            for j in i:
                yield j

    def __reversed__(self) -> Iterator[T]:
        for i in reversed(self.a):
            for j in reversed(i):
                yield j

    def __len__(self) -> int:
        return self.size

    def __repr__(self) -> str:
        return 'SortedMultiset' + str(self.a)

    def __str__(self) -> str:
        s = str(list(self))
        return '{' + s[1:len(s) - 1] + '}'

    def _find_bucket(self, x: T) -> List[T]:
        """"""
        for a in self.a:
            if x <= a[-1]:
                return a
        return a

    def __contains__(self, x: T) -> bool:
        if self.size == 0:
            return False
        a = self._find_bucket(x)
        i = bisect_left(a, x)
        return i != len(a) and a[i] == x

    def count(self, x: T) -> int:
        """"""
        return self.index_right(x) - self.index(x)

    def add(self, x: T) -> None:
        """"""
        if self.size == 0:
            self.a = [[x]]
            self.size = 1
            return
        a = self._find_bucket(x)
        insort(a, x)
        self.size += 1
        if len(a) > len(self.a) * self.REBUILD_RATIO:
            self._build()

    def discard(self, x: T) -> bool:
        """"""
        if self.size == 0:
            return False
        a = self._find_bucket(x)
        i = bisect_left(a, x)
        if i == len(a) or a[i] != x:
            return False
        a.pop(i)
        self.size -= 1
        if len(a) == 0:
            self._build()
        return True

    def lt(self, x: T) -> Union[T, None]:
        """"""
        for a in reversed(self.a):
            if a[0] < x:
                return a[bisect_left(a, x) - 1]

    def le(self, x: T) -> Union[T, None]:
        """"""
        for a in reversed(self.a):
            if a[0] <= x:
                return a[bisect_right(a, x) - 1]

    def gt(self, x: T) -> Union[T, None]:
        """"""
        for a in self.a:
            if a[-1] > x:
                return a[bisect_right(a, x)]

    def ge(self, x: T) -> Union[T, None]:
        """"""
        for a in self.a:
            if a[-1] >= x:
                return a[bisect_left(a, x)]

    def __getitem__(self, x: int) -> T:
        """"""
        if x < 0:
            x += self.size
        if x < 0:
            raise IndexError
        for a in self.a:
            if x < len(a):
                return a[x]
            x -= len(a)
        raise IndexError

    def index(self, x: T) -> int:
        """"""
        ans = 0
        for a in self.a:
            if a[-1] >= x:
                return ans + bisect_left(a, x)
            ans += len(a)
        return ans

    def index_right(self, x: T) -> int:
        """"""
        ans = 0
        for a in self.a:
            if a[-1] > x:
                return ans + bisect_right(a, x)
            ans += len(a)
        return ans

def main_MS():
    (N, Q) = NMI()
    querys = EI(Q)
    ans = 0
    A = list(range(1, N + 1))
    sz = 3000
    bnum = (N + sz - 1) // sz
    buckets = [SortedMultiset(A[i * sz:(i + 1) * sz]) for i in range(bnum)]
    for (l, r) in querys:
        (l, r) = (l - 1, r - 1)
        if l > r:
            (l, r) = (r, l)
        (al, ar) = (A[l], A[r])
        (bl, br) = (l // sz, r // sz)
        if bl == br:
            for idx in range(l + 1, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        else:
            for idx in range(l + 1, (l // sz + 1) * sz):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
            for b in range(bl + 1, br):
                ms = buckets[b]
                ans += len(ms) - ms.index_right(al)
                ans -= ms.index(al)
                ans += ms.index(ar)
                ans -= len(ms) - ms.index_right(ar)
            for idx in range(r // sz * sz, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        if al > ar:
            ans -= 1
        elif al < ar:
            ans += 1
        (A[l], A[r]) = (A[r], A[l])
        buckets[bl].discard(al)
        buckets[bl].add(ar)
        buckets[br].discard(ar)
        buckets[br].add(al)
        print(ans)

def main():
    (N, Q) = NMI()
    querys = EI(Q)
    ans = 0
    A = list(range(1, N + 1))
    sz = 3000
    bnum = (N + sz - 1) // sz
    buckets = [sorted(A[i * sz:(i + 1) * sz]) for i in range(bnum)]
    for (l, r) in querys:
        (l, r) = (l - 1, r - 1)
        if l > r:
            (l, r) = (r, l)
        (al, ar) = (A[l], A[r])
        (bl, br) = (l // sz, r // sz)
        if bl == br:
            for idx in range(l + 1, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        else:
            for idx in range(l + 1, (l // sz + 1) * sz):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
            for b in range(bl + 1, br):
                ms = buckets[b]
                ans += len(ms) - bisect.bisect_right(ms, al)
                ans -= bisect.bisect_left(ms, al)
                ans += bisect.bisect_left(ms, ar)
                ans -= len(ms) - bisect.bisect_right(ms, ar)
            for idx in range(r // sz * sz, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        if al > ar:
            ans -= 1
        elif al < ar:
            ans += 1
        (A[l], A[r]) = (A[r], A[l])
        buckets[bl].remove(al)
        buckets[bl].append(ar)
        buckets[bl].sort()
        buckets[br].remove(ar)
        buckets[br].append(al)
        buckets[br].sort()
        print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
import sys
import math
import bisect
from heapq import heapify, heappop, heappush
from collections import deque, defaultdict, Counter
from functools import lru_cache
from itertools import accumulate, combinations, permutations
MOD = 10 ** 9 + 7
MOD99 = 998244353
input = lambda : sys.stdin.readline().strip()
NI = lambda : int(input())
NMI = lambda : map(int, input().split())
NLI = lambda : list(NMI())
SI = lambda : input()
SMI = lambda : input().split()
SLI = lambda : list(SMI())
EI = lambda m: [NLI() for _ in range(m)]
import math
from bisect import bisect_left, bisect_right, insort
from typing import Generic, Iterable, Iterator, TypeVar, Union, List
T = TypeVar('T')

class SortedMultiset(Generic[T]):
    BUCKET_RATIO = 50
    REBUILD_RATIO = 170

    def _build(self, a=None) -> None:
        """"""
        if a is None:
            a = list(self)
        size = self.size = len(a)
        bucket_size = int(math.ceil(math.sqrt(size / self.BUCKET_RATIO)))
        self.a = [a[size * i // bucket_size:size * (i + 1) // bucket_size] for i in range(bucket_size)]

    def __init__(self, a: Iterable[T]=[]) -> None:
        """"""
        a = list(a)
        if not all((a[i] <= a[i + 1] for i in range(len(a) - 1))):
            a = sorted(a)
        self._build(a)

    def __iter__(self) -> Iterator[T]:
        for i in self.a:
            for j in i:
                yield j

    def __reversed__(self) -> Iterator[T]:
        for i in reversed(self.a):
            for j in reversed(i):
                yield j

    def __len__(self) -> int:
        return self.size

    def __repr__(self) -> str:
        return 'SortedMultiset' + str(self.a)

    def __str__(self) -> str:
        s = str(list(self))
        return '{' + s[1:len(s) - 1] + '}'

    def _find_bucket(self, x: T) -> List[T]:
        """"""
        for a in self.a:
            if x <= a[-1]:
                return a
        return a

    def __contains__(self, x: T) -> bool:
        if self.size == 0:
            return False
        a = self._find_bucket(x)
        i = bisect_left(a, x)
        return i != len(a) and a[i] == x

    def count(self, x: T) -> int:
        """"""
        return self.index_right(x) - self.index(x)

    def add(self, x: T) -> None:
        """"""
        if self.size == 0:
            self.a = [[x]]
            self.size = 1
            return
        a = self._find_bucket(x)
        insort(a, x)
        self.size += 1
        if len(a) > len(self.a) * self.REBUILD_RATIO:
            self._build()

    def discard(self, x: T) -> bool:
        """"""
        if self.size == 0:
            return False
        a = self._find_bucket(x)
        i = bisect_left(a, x)
        if i == len(a) or a[i] != x:
            return False
        a.pop(i)
        self.size -= 1
        if len(a) == 0:
            self._build()
        return True

    def lt(self, x: T) -> Union[T, None]:
        """"""
        for a in reversed(self.a):
            if a[0] < x:
                return a[bisect_left(a, x) - 1]

    def le(self, x: T) -> Union[T, None]:
        """"""
        for a in reversed(self.a):
            if a[0] <= x:
                return a[bisect_right(a, x) - 1]

    def gt(self, x: T) -> Union[T, None]:
        """"""
        for a in self.a:
            if a[-1] > x:
                return a[bisect_right(a, x)]

    def ge(self, x: T) -> Union[T, None]:
        """"""
        for a in self.a:
            if a[-1] >= x:
                return a[bisect_left(a, x)]

    def __getitem__(self, x: int) -> T:
        """"""
        if x < 0:
            x += self.size
        if x < 0:
            raise IndexError
        for a in self.a:
            if x < len(a):
                return a[x]
            x -= len(a)
        raise IndexError

    def index(self, x: T) -> int:
        """"""
        ans = 0
        for a in self.a:
            if a[-1] >= x:
                return ans + bisect_left(a, x)
            ans += len(a)
        return ans

    def index_right(self, x: T) -> int:
        """"""
        ans = 0
        for a in self.a:
            if a[-1] > x:
                return ans + bisect_right(a, x)
            ans += len(a)
        return ans

def main_MS():
    (N, Q) = NMI()
    querys = EI(Q)
    ans = 0
    A = list(range(1, N + 1))
    sz = 3000
    bnum = (N + sz - 1) // sz
    buckets = [SortedMultiset(A[i * sz:(i + 1) * sz]) for i in range(bnum)]
    for (l, r) in querys:
        (l, r) = (l - 1, r - 1)
        if l > r:
            (l, r) = (r, l)
        (al, ar) = (A[l], A[r])
        (bl, br) = (l // sz, r // sz)
        if bl == br:
            for idx in range(l + 1, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        else:
            for idx in range(l + 1, (l // sz + 1) * sz):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
            for b in range(bl + 1, br):
                ms = buckets[b]
                ans += len(ms) - ms.index_right(al)
                ans -= ms.index(al)
                ans += ms.index(ar)
                ans -= len(ms) - ms.index_right(ar)
            for idx in range(r // sz * sz, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        if al > ar:
            ans -= 1
        elif al < ar:
            ans += 1
        (A[l], A[r]) = (A[r], A[l])
        buckets[bl].discard(al)
        buckets[bl].add(ar)
        buckets[br].discard(ar)
        buckets[br].add(al)
        print(ans)

def main():
    (N, Q) = NMI()
    querys = EI(Q)
    ans = 0
    A = list(range(1, N + 1))
    sz = 1500
    bnum = (N + sz - 1) // sz
    buckets = [sorted(A[i * sz:(i + 1) * sz]) for i in range(bnum)]
    for (l, r) in querys:
        (l, r) = (l - 1, r - 1)
        if l > r:
            (l, r) = (r, l)
        (al, ar) = (A[l], A[r])
        (bl, br) = (l // sz, r // sz)
        if bl == br:
            for idx in range(l + 1, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        else:
            for idx in range(l + 1, (l // sz + 1) * sz):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
            for b in range(bl + 1, br):
                ms = buckets[b]
                ans += len(ms) - bisect.bisect_right(ms, al)
                ans -= bisect.bisect_left(ms, al)
                ans += bisect.bisect_left(ms, ar)
                ans -= len(ms) - bisect.bisect_right(ms, ar)
            for idx in range(r // sz * sz, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        if al > ar:
            ans -= 1
        elif al < ar:
            ans += 1
        (A[l], A[r]) = (A[r], A[l])
        buckets[bl].remove(al)
        buckets[bl].append(ar)
        buckets[bl].sort()
        buckets[br].remove(ar)
        buckets[br].append(al)
        buckets[br].sort()
        print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
import sys
import math
import bisect
from heapq import heapify, heappop, heappush
from collections import deque, defaultdict, Counter
from functools import lru_cache
from itertools import accumulate, combinations, permutations
MOD = 10 ** 9 + 7
MOD99 = 998244353
input = lambda : sys.stdin.readline().strip()
NI = lambda : int(input())
NMI = lambda : map(int, input().split())
NLI = lambda : list(NMI())
SI = lambda : input()
SMI = lambda : input().split()
SLI = lambda : list(SMI())
EI = lambda m: [NLI() for _ in range(m)]
import math
from bisect import bisect_left, bisect_right, insort
from typing import Generic, Iterable, Iterator, TypeVar, Union, List
T = TypeVar('T')

class SortedMultiset(Generic[T]):
    BUCKET_RATIO = 50
    REBUILD_RATIO = 170

    def _build(self, a=None) -> None:
        """"""
        if a is None:
            a = list(self)
        size = self.size = len(a)
        bucket_size = int(math.ceil(math.sqrt(size / self.BUCKET_RATIO)))
        self.a = [a[size * i // bucket_size:size * (i + 1) // bucket_size] for i in range(bucket_size)]

    def __init__(self, a: Iterable[T]=[]) -> None:
        """"""
        a = list(a)
        if not all((a[i] <= a[i + 1] for i in range(len(a) - 1))):
            a = sorted(a)
        self._build(a)

    def __iter__(self) -> Iterator[T]:
        for i in self.a:
            for j in i:
                yield j

    def __reversed__(self) -> Iterator[T]:
        for i in reversed(self.a):
            for j in reversed(i):
                yield j

    def __len__(self) -> int:
        return self.size

    def __repr__(self) -> str:
        return 'SortedMultiset' + str(self.a)

    def __str__(self) -> str:
        s = str(list(self))
        return '{' + s[1:len(s) - 1] + '}'

    def _find_bucket(self, x: T) -> List[T]:
        """"""
        for a in self.a:
            if x <= a[-1]:
                return a
        return a

    def __contains__(self, x: T) -> bool:
        if self.size == 0:
            return False
        a = self._find_bucket(x)
        i = bisect_left(a, x)
        return i != len(a) and a[i] == x

    def count(self, x: T) -> int:
        """"""
        return self.index_right(x) - self.index(x)

    def add(self, x: T) -> None:
        """"""
        if self.size == 0:
            self.a = [[x]]
            self.size = 1
            return
        a = self._find_bucket(x)
        insort(a, x)
        self.size += 1
        if len(a) > len(self.a) * self.REBUILD_RATIO:
            self._build()

    def discard(self, x: T) -> bool:
        """"""
        if self.size == 0:
            return False
        a = self._find_bucket(x)
        i = bisect_left(a, x)
        if i == len(a) or a[i] != x:
            return False
        a.pop(i)
        self.size -= 1
        if len(a) == 0:
            self._build()
        return True

    def lt(self, x: T) -> Union[T, None]:
        """"""
        for a in reversed(self.a):
            if a[0] < x:
                return a[bisect_left(a, x) - 1]

    def le(self, x: T) -> Union[T, None]:
        """"""
        for a in reversed(self.a):
            if a[0] <= x:
                return a[bisect_right(a, x) - 1]

    def gt(self, x: T) -> Union[T, None]:
        """"""
        for a in self.a:
            if a[-1] > x:
                return a[bisect_right(a, x)]

    def ge(self, x: T) -> Union[T, None]:
        """"""
        for a in self.a:
            if a[-1] >= x:
                return a[bisect_left(a, x)]

    def __getitem__(self, x: int) -> T:
        """"""
        if x < 0:
            x += self.size
        if x < 0:
            raise IndexError
        for a in self.a:
            if x < len(a):
                return a[x]
            x -= len(a)
        raise IndexError

    def index(self, x: T) -> int:
        """"""
        ans = 0
        for a in self.a:
            if a[-1] >= x:
                return ans + bisect_left(a, x)
            ans += len(a)
        return ans

    def index_right(self, x: T) -> int:
        """"""
        ans = 0
        for a in self.a:
            if a[-1] > x:
                return ans + bisect_right(a, x)
            ans += len(a)
        return ans

def main():
    (N, Q) = NMI()
    querys = EI(Q)
    ans = 0
    A = list(range(1, N + 1))
    sz = 3000
    bnum = (N + sz - 1) // sz
    buckets = [SortedMultiset(A[i * sz:(i + 1) * sz]) for i in range(bnum)]
    for (l, r) in querys:
        (l, r) = (l - 1, r - 1)
        if l > r:
            (l, r) = (r, l)
        (al, ar) = (A[l], A[r])
        (bl, br) = (l // sz, r // sz)
        if bl == br:
            for idx in range(l + 1, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        else:
            for idx in range(l + 1, (l // sz + 1) * sz):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
            for b in range(bl + 1, br):
                ms = buckets[b]
                ans += len(ms) - ms.index_right(al)
                ans -= ms.index(al)
                ans += ms.index(ar)
                ans -= len(ms) - ms.index_right(ar)
            for idx in range(r // sz * sz, r):
                a = A[idx]
                if a > al:
                    ans += 1
                elif a < al:
                    ans -= 1
                if a > ar:
                    ans -= 1
                elif a < ar:
                    ans += 1
        if al > ar:
            ans -= 1
        elif al < ar:
            ans += 1
        (A[l], A[r]) = (A[r], A[l])
        buckets[bl].discard(al)
        buckets[bl].add(ar)
        buckets[br].discard(ar)
        buckets[br].add(al)
        print(ans)
if __name__ == '__main__':
    main()