Link to this code: https://cses.fi/paste/cf5b854d677858a526a507/
/*
  author: @ankingcodes
  created: 2021-07-18 11:21:01.574877
*/
        
#include<bits/stdc++.h>
#include<algorithm>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;
#define ll long long
#define MOD 1000000007

typedef tree<int, null_type, less<int>, rb_tree_tag,
                tree_order_statistics_node_update> PBDS;

typedef tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag,
                tree_order_statistics_node_update> pairPBDS;

int main(){
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ll n, m; cin >> n >> m;
  vector<ll> a(n+1), pos(n+1);
  for (int i=1;i<=n;i++) {
    cin >> a[i];
    pos[a[i]] = i;
  }
  int ans = 1;
  for (int i=1;i<n;i++)
    if(pos[i] > pos[i+1]) ans+=1;
  int l, r; 
  set<pair<int, int>> up;
  while(m--) {
    cin >> l >> r;
    if (a[l]+1 <= n) up.insert({a[l], a[l]+1});
    if (a[l]-1 >= 1) up.insert({a[l]-1, a[l]});
    if (a[r]+1 <= n) up.insert({a[r], a[r]+1});
    if (a[r]-1 >= 1) up.insert({a[r]-1, a[r]});
    for (auto x: up) 
      ans-=(pos[x.first]>pos[x.second]);
    swap(a[l], a[r]);
    pos[a[l]] = l;
    pos[a[r]] = r;
    for (auto x: up) 
      ans+=(pos[x.first]>pos[x.second]);
    cout << ans << endl;
    up.clear();
  }
  return 0;
}