-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectingNumbers2.cpp
More file actions
57 lines (49 loc) · 1.24 KB
/
CollectingNumbers2.cpp
File metadata and controls
57 lines (49 loc) · 1.24 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
//Collecting Numbers II - https://cses.fi/problemset/task/2217/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
const ll INF = 1e18;
void solve() {
int n, m;
cin >> n >> m;
vector<int> a(n), pos(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
a[i]--;
pos[a[i]] = i;
}
int ans = 1;
for (int i = 0; i < n - 1; i++) {
if (pos[i] > pos[i + 1])
ans++;
}
auto rebalance = [&](int x, int y, int delta) {
int mn = min(x, y), mx = max(x, y);
if (x < n - 1 && pos[x] > pos[x + 1]) ans += delta;
if (y < n - 1 && pos[y] > pos[y + 1]) ans += delta;
if (mn - 1 >= 0 && pos[mn - 1] > pos[mn]) ans += delta;
if (mx - 1 != mn && pos[mx - 1] > pos[mx]) ans += delta;
};
for (int op = 0; op < m; op++) {
int i, j;
cin >> i >> j;
i--, j--;
int x = a[i], y = a[j];
rebalance(x, y, -1);
swap(pos[x], pos[y]);
swap(a[i], a[j]);
rebalance(x, y, 1);
cout << ans << endl;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int T = 1;
// cin >> T;
while (T--) {
solve();
}
return 0;
}