-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollecting_numbers_2.py
More file actions
84 lines (61 loc) · 1.56 KB
/
collecting_numbers_2.py
File metadata and controls
84 lines (61 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# =======================
# Python CP Template
# (bits/stdc++.h equivalent)
# =======================
import sys
# Fast I/O
input = sys.stdin.readline
# Common imports
from collections import defaultdict, deque, Counter
from itertools import combinations, permutations, product, accumulate
from functools import lru_cache, reduce
import heapq
import bisect
# Constants
MAX = float('inf')
MIN = float('-inf')
MOD = 10**9 + 7
# =======================
# Main Logic
# =======================
def solve():
n, m = map(int, input().split())
arr = list(map(int, input().split()))
pos = [0] * (n + 1)
for i in range(n):
pos[arr[i]] = i
ans = 1
for i in range(2, n + 1):
if pos[i] < pos[i - 1]:
ans += 1
res = []
for _ in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
x = arr[a]
y = arr[b]
affected = set()
for v in (x, y):
if v > 1:
affected.add((v - 1, v))
if v < n:
affected.add((v, v + 1))
# remove old contributions
for u, v in affected:
if pos[u] > pos[v]:
ans -= 1
# swap in arr
arr[a], arr[b] = arr[b], arr[a]
pos[x], pos[y] = pos[y], pos[x]
# add new contributions
for u, v in affected:
if pos[u] > pos[v]:
ans += 1
res.append(str(ans))
print("\n".join(res))
# =======================
# Entry Point
# =======================
if __name__ == "__main__":
solve()