Problem:
Swap and Inversion Number
The inversion number of a sequence of length $N$ $\{a_1, a_2,.... . a_N\}$ is the total number of pairs ($a_i, a_j$) of elements satisfying $1 \leq i < j \leq N$ and $a_i > a_j$.
The inversion number of a sequence is also known as the number of exchanges in the elementary alignment algorithm, bubble sort.
In this problem, we perform the operation of exchanging the values of two elements in a number sequence and output the inversion number of the sequence after the exchange.
Wreate a program that reads a number sequence and information about multiple operations and outputs the result of each operation. Each operation after the first one shall be performed on the number sequence obtained as a result of the immediately preceding operation.
Input
The input is given in the following form.
$N$
$a_1$ $a_2$ ... $a_N$
$M$
$b_1$ $e_1$
$b_2$ $e_2$
:
$b_M$ $e_M$
The first line gives the number of elements of the sequence $N$ ($2 \leq N \leq 500,000$); the second line gives the value of the $i$-th element of the sequence $a_i$ ($0 \leq a_i \leq 1,000,000,000$). The values of all elements are different (if $i \ne j$, then $a_i \ne a_j$). In the subsequent line, the number of operations $M$ ($1 \leq M \leq 30,000$) is given. In the following $M$ lines, the pair of integers $b_i$ and $e_i$ ($1 \leq b_i < e_i \leq N$) representing the information of the $i$-th operation are given. $b_i$ and $e_i$ indicate that it is the values of the $b_i$-th and $e_i$-th elements of the sequence of numbers that are exchanged in the $i$-th operation.
Output
The output consists of $M$ rows. For each operation, output the result of the operation in a line.
Sample Input and Output
Sample Input
6
4 6 5 3 1 2
3
2 4
3 6
1 5
Sample Output
9
8
3

Submitted solutions:

code_snippet: // AOJ #451
// Swap and Inversion Number 2025.2.9
 
#include <bits/stdc++.h>
using namespace std;

#define gc() getchar_unlocked()
#define pc(c) putchar_unlocked(c)

int Cin() {  // 整数の入力
	int n = 0, c = gc();
	if (c == '-') {	c = gc();
		do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
		return -n;
	}
	do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
	return n;
}

void Cout(int n) { // 整数の表示（出力）
	char b[30];
	if (!n) pc('0');
	else {
		if (n < 0) pc('-'), n = -n;
		int i = 0; while (n) b[i++] = n % 10 + '0', n /= 10;
		while (i--) pc(b[i]);
	}
	pc('\n');
}

int main() {
    int N = Cin(); 
    vector<int> A(N+1);
    vector<int> tmp(N);
    for (int i = 1; i <= N; i++){
        A[i] = Cin();
        tmp[i-1] = A[i];
    }
    sort(tmp.begin(), tmp.end());
    tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end());
    for (int i = 1; i <= N; i++){
        int rank = int(lower_bound(tmp.begin(), tmp.end(), A[i]) - tmp.begin()) + 1;
        A[i] = rank;
    }
    vector<int> fenw(N+1,0);
    auto fenw_update = [&](int idx, int delta) {
        for(; idx <= N; idx += idx & -idx) fenw[idx] += delta;
    };
    auto fenw_query = [&](int idx) -> int {
        int s = 0;
        for(; idx > 0; idx -= idx & -idx) s += fenw[idx];
        return s;
    };
    long long invCount = 0;
    for (int i = 1; i <= N; i++){
        int cnt = (i - 1) - fenw_query(A[i]);
        invCount += cnt;
        fenw_update(A[i], 1);
    }
 
    const int B = 1000;
    int nblocks = (N + B - 1) / B;
    vector<int> blockL(nblocks), blockR(nblocks), blockId(N+1);
    vector<vector<int>> blocks(nblocks);
    for (int b = 0; b < nblocks; b++){
        blockL[b] = b * B + 1;
        blockR[b] = min(N, (b+1) * B);
        blocks[b].resize(blockR[b] - blockL[b] + 1);
        for (int i = blockL[b]; i <= blockR[b]; i++){
            blockId[i] = b;
            blocks[b][i - blockL[b]] = A[i];
        }
        sort(blocks[b].begin(), blocks[b].end());
    }
 
    auto query_range = [&](int L, int R, int low, int high) -> int {
        if(L > R) return 0;
        int res = 0;
        int bL = blockId[L], bR = blockId[R];
        if(bL == bR){
            for(int i = L; i <= R; i++){
                if(A[i] > low && A[i] < high) res++;
            }
            return res;
        }
        int endFirst = blockR[bL];
        for (int i = L; i <= endFirst; i++){
            if(A[i] > low && A[i] < high) res++;
        }
        for (int b = bL + 1; b < bR; b++){
            int cnt = int(lower_bound(blocks[b].begin(), blocks[b].end(), high) - 
                          upper_bound(blocks[b].begin(), blocks[b].end(), low));
            res += cnt;
        }
        int startLast = blockL[bR];
        for (int i = startLast; i <= R; i++){
            if(A[i] > low && A[i] < high) res++;
        }
        return res;
    };
 
    auto update_position = [&](int pos, int new_val) {
        int b = blockId[pos];
        int old_val = A[pos];
        auto it = std::lower_bound(blocks[b].begin(), blocks[b].end(), old_val);
        if(it != blocks[b].end() && *it == old_val)
            blocks[b].erase(it);
        auto it2 = std::upper_bound(blocks[b].begin(), blocks[b].end(), new_val);
        blocks[b].insert(it2, new_val);
        A[pos] = new_val;
    };
 
    auto rebuild_block = [&](int b) {
        blocks[b].clear();
        blocks[b].resize(blockR[b] - blockL[b] + 1);
        for (int i = blockL[b]; i <= blockR[b]; i++){
            blocks[b][i - blockL[b]] = A[i];
        }
        sort(blocks[b].begin(), blocks[b].end());
    };
 
    int M = Cin(); 
    for (int op = 0; op < M; op++){
        int i = Cin(), j = Cin(); 
 
        int x = A[i], y = A[j];
        int low = min(x,y), high = max(x,y);
 
        int countBetween = 0;
        if(j - i > 1)
            countBetween = query_range(i+1, j-1, low, high);
 
        int delta = 0;
        if(x < y) delta = 2 * countBetween + 1;
        else      delta = - (2 * countBetween + 1);
 
        invCount += delta;
        cout << invCount << endl;
 
        int b1 = blockId[i], b2 = blockId[j];
        if(b1 == b2){
            swap(A[i], A[j]);
            rebuild_block(b1);
        } else {
            int temp_x = A[i], temp_y = A[j];
            update_position(i, temp_y);
            update_position(j, temp_x);
        }
    }
    return 0;
}
accuracy: 1
time_ms: 620
memory_kb: 12796
final_rank: 1

code_snippet: #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp>


using namespace std;
using namespace __gnu_pbds;

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

const int N = 5e5 + 10;

vector<ordered_set>t(4 * N);
vector<int>a(N);

void build(int v, int tl, int tr){
    if (tl == tr){
        t[v].insert(a[tl]);
        return;
    }

    int tm = (tl + tr) / 2;
    build(v * 2, tl, tm);
    build(v * 2 + 1, tm + 1, tr);
    t[v] = t[v * 2];
    for (auto x : t[v * 2 + 1])t[v].insert(x);
} 

pair<int, int> qry(int v, int tl, int tr, int l, int r, int x){
    if (tl > r || tr < l)return {0, 0};
    if (l <= tl && tr <= r){
        int cls = t[v].order_of_key(x);
        int cgr = (tr - tl + 1) - cls;
        return {cls, cgr};
    }
    int tm = (tl + tr) / 2;
    pair<int, int>resl= qry(v * 2, tl, tm, l, r, x);
    pair<int, int>resr = qry(v * 2 + 1, tm + 1, tr, l, r, x);
    return {resl.first + resr.first, resl.second + resr.second};
}

void upd(int v, int tl, int tr, int x, int y){
    if (t[v].find(x) == t[v].end())return;
    if (tl == tr){
        t[v].clear();
        t[v].insert(y);
        return;
    }

    int tm = (tl + tr) / 2;
    upd(v * 2, tl, tm, x, y);
    upd(v * 2 + 1, tm + 1, tr, x, y);
    t[v].erase(x);
    t[v].insert(y);
}

void print(int v, int tl, int tr){
    if (tl == tr)
        cout << *t[v].begin() << ' ';
    else {
        int tm = (tl + tr) / 2;
        print(v * 2, tl, tm);
        print(v * 2 + 1, tm + 1, tr);
    }
}


int fen[N];
int sum(int r){
    int res = 0;
    for (; r > 0; r -= r & -r)
        res += fen[r];
    return res;
}

void add (int k, int v){
    for (; k < N; k += k & -k)
        fen[k] += v;
}

signed main(){
    int n;
    cin >> n;
    vector<int>b(n);
    for (int i = 0; i < n; i++){
        cin >> a[i];
        b[i] = a[i];
    }
    sort(b.begin(), b.end());
    int cinv = 0;
    for (int i = 0; i < n; i++){
        int id = lower_bound(b.begin(), b.end(), a[i]) - b.begin();
        a[i] = id + 1;
        cinv += i - sum(id + 1);
        add(id + 1, 1);
    }
    build(1, 0, n - 1);
    int q;
    cin >> q;
    while(q--){
        int i, j;
        cin >> i >> j;
        i--;j--;
        pair<int, int> il = qry(1, 0, n - 1, 0, i - 1, a[i]);
        pair<int, int> ir = qry(1, 0, n - 1, i + 1, n - 1, a[i]);
        pair<int, int> jl = qry(1, 0, n - 1, 0, j - 1, a[j]);
        pair<int, int> jr = qry(1, 0, n - 1, j + 1, n - 1, a[j]);
        cinv -= il.second + ir.first;
        cinv -= jl.second + jr.first;
        if (a[i] > a[j])cinv++;
        upd(1, 0, n - 1, a[i], -a[j]);
        upd(1, 0, n - 1, a[j], -a[i]);
        upd(1, 0, n - 1, -a[i], a[i]);
        upd(1, 0, n - 1, -a[j], a[j]);
        //print(1, 0, n - 1);
        //cout << endl;
        swap(a[i], a[j]);
        il = qry(1, 0, n - 1, 0, i - 1, a[i]);
        ir = qry(1, 0, n - 1, i + 1, n - 1, a[i]);
        jl = qry(1, 0, n - 1, 0, j - 1, a[j]);
        jr = qry(1, 0, n - 1, j + 1, n - 1, a[j]);
        cinv += il.second + ir.first;
        cinv += jl.second + jr.first;
        cout << cinv << endl;
    }
    return 0;
}
accuracy: 0.05
time_ms: 70
memory_kb: 161144
final_rank: 20

code_snippet: #include<bits/stdc++.h>
using namespace std;

// #include<atcoder/all>
// using namespace atcoder;
// using mint=atcoder::modint998244353;

#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

#define int long long

signed main(){
	int n;cin>>n;

	vector<int> a(n);for(auto&&e:a)cin>>e;

	auto slv=[&](auto slv,vector<int> v)->int {
		if(v.size()==1)return 0;
		vector<int> vl(v.begin(),v.begin()+v.size()/2);
		vector<int> vr(v.begin()+v.size()/2,v.end());
		int res=slv(slv,vl)+slv(slv,vr);
		sort(vr.begin(),vr.end());
		for(auto&&e:vl){
			res+=lower_bound(vr.begin(),vr.end(),e)-vr.begin();
		}
		return res;
	};

	int ans=slv(slv,a);

	const int B=1000;

	vector<vector<int>> bs((n-1)/B+1);

	for(int i=0;i<n;i++){
		bs[i/B].push_back(a[i]);
	}
	for(auto&&v:bs)sort(v.begin(),v.end());

	int q;cin>>q;

	while(q--){
		int x,y;cin>>x>>y;x--;y--;

		for(int i=0;i<bs.size();i++){
			if(x<i*B){
				ans-=bs[i].end()-lower_bound(bs[i].begin(),bs[i].end(),a[x]);
			}
			if(i*B+B-1<x){
				ans-=lower_bound(bs[i].begin(),bs[i].end(),a[x])-bs[i].begin();
			}
			if(y<i*B){
				ans-=bs[i].end()-lower_bound(bs[i].begin(),bs[i].end(),a[y]);
			}
			if(i*B+B-1<y){
				ans-=lower_bound(bs[i].begin(),bs[i].end(),a[y])-bs[i].begin();
			}
		}

		for(int i=x/B*B;i<min(n,x/B*B+B);i++){
			if(i<x){
				if(a[i]>a[x])ans--;
			}else{
				if(a[i]<a[x])ans--;
			}
		}

		for(int i=y/B*B;i<min(n,y/B*B+B-1);i++){
			if(i<y){
				if(a[i]>a[y])ans--;
			}else{
				if(a[i]<a[y])ans--;
			}
		}

		ans+=(a[x]>a[y]);

		bs[x/B].erase(find(bs[x/B].begin(),bs[x/B].end(),a[x]));
		bs[x/B].push_back(a[y]);
		sort(bs[x/B].begin(),bs[x/B].end());
		
		bs[y/B].erase(find(bs[y/B].begin(),bs[y/B].end(),a[y]));
		bs[y/B].push_back(a[x]);
		sort(bs[y/B].begin(),bs[y/B].end());

		swap(a[x],a[y]);

		ans=-ans;

		for(int i=0;i<bs.size();i++){
			if(x<i*B){
				ans-=bs[i].end()-lower_bound(bs[i].begin(),bs[i].end(),a[x]);
			}
			if(i*B+B-1<x){
				ans-=lower_bound(bs[i].begin(),bs[i].end(),a[x])-bs[i].begin();
			}
			if(y<i*B){
				ans-=bs[i].end()-lower_bound(bs[i].begin(),bs[i].end(),a[y]);
			}
			if(i*B+B-1<y){
				ans-=lower_bound(bs[i].begin(),bs[i].end(),a[y])-bs[i].begin();
			}
		}

		for(int i=x/B*B;i<min(n,x/B*B+B);i++){
			if(i<x){
				if(a[i]>a[x])ans--;
			}else{
				if(a[i]<a[x])ans--;
			}
		}

		for(int i=y/B*B;i<min(n,y/B*B+B-1);i++){
			if(i<y){
				if(a[i]>a[y])ans--;
			}else{
				if(a[i]<a[y])ans--;
			}
		}

		ans+=(a[x]>a[y]);

		ans=-ans;

		cout<<ans<<endl;
	}
}
accuracy: 0.6
time_ms: 230
memory_kb: 3724
final_rank: 19

code_snippet: #include <bits/stdc++.h>


namespace zawa {

template <class T>
class AdditiveGroup {
public:
    using Element = T;
    static constexpr T identity() noexcept {
        return T{};
    }
    static constexpr T operation(const T& l, const T& r) noexcept {
        return l + r;
    }
    static constexpr T inverse(const T& v) noexcept {
        return -v;
    }
};

} // namespace zawa



namespace zawa {

using i16 = std::int16_t;
using i32 = std::int32_t;
using i64 = std::int64_t;
using i128 = __int128_t;

using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;

using usize = std::size_t;

} // namespace zawa

#include <type_traits>

namespace zawa {

template <class Group>
class FenwickTree {
private:
    using Value = typename Group::Element;

    usize n_;
    u32 bitWidth_;
    std::vector<Value> a_, dat_;

    constexpr i32 lsb(i32 x) const noexcept {
        return x & -x;
    }
    
    // a[i] <- a[i] + v
    void addDat(i32 i, const Value& v) {
        assert(0 <= i and i < static_cast<i32>(n_));
        for ( i++ ; i < static_cast<i32>(dat_.size()) ; i += lsb(i)) {
            dat_[i] = Group::operation(dat_[i], v);
        }
    }

    // return a[0] + a[1] + .. + a[i - 1]
    Value product(i32 i) const {
        assert(0 <= i and i <= static_cast<i32>(n_));
        Value res{ Group::identity() };
        for ( ; i > 0 ; i -= lsb(i)) {
            res = Group::operation(res, dat_[i]);
        }
        return res;
    }

public:
    FenwickTree() : n_{}, bitWidth_{}, a_{}, dat_{} {}

    FenwickTree(usize n) : n_{ n }, bitWidth_{ std::__lg(static_cast<u32>(n)) + 1 }, a_(n), dat_(n + 1, Group::identity()) {
        dat_.shrink_to_fit();
    }

    FenwickTree(const std::vector<Value>& a) : n_{ a.size() }, bitWidth_{ std::__lg(static_cast<u32>(a.size())) + 1 }, a_(a), dat_(a.size() + 1, Group::identity()) {
        dat_.shrink_to_fit();  
        for (i32 i{} ; i < static_cast<i32>(n_) ; i++) {
            addDat(i, a[i]);
        }
    }

    // return a[i]
    const Value& get(usize i) const noexcept {
        assert(i < n_);
        return a_[i];
    }

    // return a[i]
    const Value& operator[](usize i) const noexcept {
        assert(i < n_);
        return a_[i];
    }

    usize size() const noexcept {
        return n_;
    }

    // a[i] <- a[i] + v
    void operation(usize i, const Value& v) {
        assert(i < n_);
        addDat(i, v);
        a_[i] = Group::operation(a_[i], v);
    }

    // a[i] <- v
    void set(usize i, const Value& v) {
        assert(i < n_);
        addDat(i, Group::operation(Group::inverse(a_[i]), v));
        a_[i] = v;
    }

    // return a[0] + a[1] + ... + a[r - 1]
    Value prefixProduct(usize r) const {
        assert(r <= n_);
        return product(r);
    }

    // return a[l] + a[l + 1] ... + a[r - 1]
    Value product(usize l, usize r) const {
        assert(l <= r and r <= n_);
        return Group::operation(Group::inverse(product(l)), product(r));
    }

    template <class Function>
    u32 maxRight(usize l, const Function& f) const {
        static_assert(std::is_convertible_v<decltype(f), std::function<bool(Value)>>, "maxRight's argument f must be function bool(T)");
        assert(l < n_);
        Value sum{ Group::inverse(product(l)) }; 
        u32 r{};
        for (u32 bit{ bitWidth_ } ; bit ; ) {
            bit--;
            u32 nxt{ r | (1u << bit) };
            if (nxt < dat_.size() and f(Group::operation(sum, dat_[nxt]))) {
                sum = Group::operation(sum, dat_[nxt]);
                r = std::move(nxt);
            }
        }
        assert(l <= r);
        return r;
    }

    template <class Function>
    u32 minLeft(usize r, const Function& f) const {
        static_assert(std::is_convertible_v<decltype(f), std::function<bool(Value)>>, "minLeft's argument f must be function bool(T)");
        assert(r <= n_);
        Value sum{ product(r) };
        u32 l{};
        for (u32 bit{ bitWidth_ } ; bit ; ) {
            bit--;
            u32 nxt{ l | (1u << bit) };
            if (nxt <= r and not f(Group::operation(Group::inverse(dat_[nxt]), sum))) {
                sum = Group::operation(Group::inverse(dat_[nxt]), sum);
                l = std::move(nxt);
            }
        }
        assert(l <= r);
        return l;
    }

    // debug print
    friend std::ostream& operator<<(std::ostream& os, const FenwickTree& ft) {
        for (u32 i{} ; i <= ft.size() ; i++) {
            os << ft.prefixProduct(i) << (i == ft.size() ? "" : " ");
        }
        return os;
    }

};


} // namespace zawa



namespace zawa {

template <class InputIterator>
u64 InversionNumber(InputIterator first, InputIterator last) {
    assert((usize)std::distance(first, last) >= usize{0});
    std::vector<std::remove_reference_t<decltype(*first)>> A(first, last);
    auto rec{[&](auto rec, usize L, usize R) -> u64 {
        if (R - L <= usize{1}) return 0; 
        usize M{(L + R) >> 1};
        u64 res{rec(rec, L, M) + rec(rec, M, R)};
        std::vector<u64> tmp(R - L);
        usize i{L}, j{M}, k{};
        while (i < M and j < R) {
            if (A[i] <= A[j]) {
                tmp[k++] = A[i++];
            }
            else {
                res += M - i;
                tmp[k++] = A[j++];
            }
        }
        while (i < M) tmp[k++] = A[i++];
        while (j < R) tmp[k++] = A[j++];
        for (usize l{L} ; l < R ; l++) {
            A[l] = tmp[l - L];
        }
        return res;
    }};
    return rec(rec, usize{0}, usize{A.size()});
}

template <class InputIterator>
bool InversionParity(InputIterator first, InputIterator last) {
    assert((usize)std::distance(first, last) >= usize{0});
    std::vector<std::remove_reference_t<decltype(*first)>> A(first, last);
    auto rec{[&](auto rec, usize L, usize R) -> bool {
        if (R - L <= usize{1}) return 0; 
        usize M{(L + R) >> 1};
        bool res{rec(rec, L, M) != rec(rec, M, R)};
        std::vector<u64> tmp(R - L);
        usize i{L}, j{M}, k{};
        while (i < M and j < R) {
            if (A[i] <= A[j]) {
                tmp[k++] = A[i++];
            }
            else {
                res ^= (M - i) & 1;
                tmp[k++] = A[j++];
            }
        }
        while (i < M) tmp[k++] = A[i++];
        while (j < R) tmp[k++] = A[j++];
        for (usize l{L} ; l < R ; l++) {
            A[l] = tmp[l - L];
        }
        return res;
    }};
    return rec(rec, usize{0}, usize{A.size()});
}

} // namespace zawa
using namespace zawa;

const int sq{3000};

int main() {
    std::cin.tie(nullptr)->sync_with_stdio(false);

    int N;
    std::cin >> N;
    std::vector<int> A(N);
    for (auto& a : A) std::cin >> a;
    int M;
    std::cin >> M;
    std::vector<int> B(M), E(M);
    for (int i{} ; i < M ; i++) {
        std::cin >> B[i] >> E[i];
        B[i]--; E[i]--;
    }
    const int sz{(N + sq - 1) / sq};
    std::vector<std::vector<int>> app(sz);
    for (int i{} ; i < N ; i++) {
        app[i / sq].push_back(A[i]);
    }
    {
        std::vector<int> tmp(A);
        for (int i{} ; i < M ; i++) {
            std::swap(tmp[B[i]], tmp[E[i]]);
            app[B[i] / sq].push_back(tmp[B[i]]);
            app[E[i] / sq].push_back(tmp[E[i]]);
        }
    }
    for (int i{} ; i < sz ; i++) {
        std::sort(app[i].begin(), app[i].end());
        app[i].erase(std::unique(app[i].begin(), app[i].end()), app[i].end());
    }
    std::vector<FenwickTree<AdditiveGroup<int>>> fen(sz);
    auto comp{[&](int i, int x) -> int {
        return (int)std::distance(app[i].begin(), std::lower_bound(app[i].begin(), app[i].end(), x));
    }};
    for (int i{} ; i < sz ; i++) {
        fen[i] = FenwickTree<AdditiveGroup<int>>(app[i].size());
        for (int j{i * sq} ; j < std::min(N, (i + 1) * sq) ; j++) {
            fen[i].operation(comp(i, A[j]), 1);
        }
    }
    // j = 0, 1, ..., i - 1について、x以上の値の数
    auto pref{[&](int i, int x) -> int {
        int pos{i / sq}, res{};
        for (int j{} ; j < pos ; j++) {
            res += fen[j].product(comp(j, x), app[j].size());
        }
        for (int j{pos * sq} ; j < i ; j++) {
            if (A[j] >= x) res++;
        }
        return res;
    }};
    // j = i + 1, i + 2, ..., N - 1について、x以上の値の数
    auto suf{[&](int i, int x) -> int {
        int pos{i / sq}, res{};
        for (int j{i + 1} ; j < std::min(N, (pos + 1) * sq) ; j++) {
            if (A[j] >= x) res++;
        }
        for (int j{pos + 1} ; j < sz ; j++) {
            res += fen[j].product(comp(j, x), app[j].size());
        }
        return res;
    }};
    long long inv{(long long)InversionNumber(A.begin(), A.end())};
    for (int i{} ; i < M ; i++) {
        int u{A[B[i]]}, v{A[E[i]]};
        // A[B[i]] <- v
        inv -= pref(B[i], A[B[i]] + 1);
        inv -= (N - B[i] - 1) - suf(B[i], A[B[i]]);
        fen[B[i] / sq].operation(comp(B[i] / sq, A[B[i]]), -1);
        fen[B[i] / sq].operation(comp(B[i] / sq, v), 1);
        A[B[i]] = v;
        inv += pref(B[i], A[B[i]] + 1);
        inv += (N - B[i] - 1) - suf(B[i], A[B[i]]);
        // A[E[i]] <- u
        inv -= pref(E[i], A[E[i]] + 1);
        inv -= (N - E[i] - 1) - suf(E[i], A[E[i]]);
        fen[E[i] / sq].operation(comp(E[i] / sq, A[E[i]]), -1);
        fen[E[i] / sq].operation(comp(E[i] / sq, u), 1);
        A[E[i]] = u;
        inv += pref(E[i], A[E[i]] + 1);
        inv += (N - E[i] - 1) - suf(E[i], A[E[i]]);
        std::cout << inv << '\n';
    }
}
accuracy: 1
time_ms: 1910
memory_kb: 20216
final_rank: 5

code_snippet: #include <bits/stdc++.h>


namespace zawa {

template <class T>
class AdditiveGroup {
public:
    using Element = T;
    static constexpr T identity() noexcept {
        return T{};
    }
    static constexpr T operation(const T& l, const T& r) noexcept {
        return l + r;
    }
    static constexpr T inverse(const T& v) noexcept {
        return -v;
    }
};

} // namespace zawa



namespace zawa {

using i16 = std::int16_t;
using i32 = std::int32_t;
using i64 = std::int64_t;
using i128 = __int128_t;

using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;

using usize = std::size_t;

} // namespace zawa

#include <type_traits>

namespace zawa {

template <class Group>
class FenwickTree {
private:
    using Value = typename Group::Element;

    usize n_;
    u32 bitWidth_;
    std::vector<Value> a_, dat_;

    constexpr i32 lsb(i32 x) const noexcept {
        return x & -x;
    }
    
    // a[i] <- a[i] + v
    void addDat(i32 i, const Value& v) {
        assert(0 <= i and i < static_cast<i32>(n_));
        for ( i++ ; i < static_cast<i32>(dat_.size()) ; i += lsb(i)) {
            dat_[i] = Group::operation(dat_[i], v);
        }
    }

    // return a[0] + a[1] + .. + a[i - 1]
    Value product(i32 i) const {
        assert(0 <= i and i <= static_cast<i32>(n_));
        Value res{ Group::identity() };
        for ( ; i > 0 ; i -= lsb(i)) {
            res = Group::operation(res, dat_[i]);
        }
        return res;
    }

public:
    FenwickTree() : n_{}, bitWidth_{}, a_{}, dat_{} {}

    FenwickTree(usize n) : n_{ n }, bitWidth_{ std::__lg(static_cast<u32>(n)) + 1 }, a_(n), dat_(n + 1, Group::identity()) {
        dat_.shrink_to_fit();
    }

    FenwickTree(const std::vector<Value>& a) : n_{ a.size() }, bitWidth_{ std::__lg(static_cast<u32>(a.size())) + 1 }, a_(a), dat_(a.size() + 1, Group::identity()) {
        dat_.shrink_to_fit();  
        for (i32 i{} ; i < static_cast<i32>(n_) ; i++) {
            addDat(i, a[i]);
        }
    }

    // return a[i]
    const Value& get(usize i) const noexcept {
        assert(i < n_);
        return a_[i];
    }

    // return a[i]
    const Value& operator[](usize i) const noexcept {
        assert(i < n_);
        return a_[i];
    }

    usize size() const noexcept {
        return n_;
    }

    // a[i] <- a[i] + v
    void operation(usize i, const Value& v) {
        assert(i < n_);
        addDat(i, v);
        a_[i] = Group::operation(a_[i], v);
    }

    // a[i] <- v
    void set(usize i, const Value& v) {
        assert(i < n_);
        addDat(i, Group::operation(Group::inverse(a_[i]), v));
        a_[i] = v;
    }

    // return a[0] + a[1] + ... + a[r - 1]
    Value prefixProduct(usize r) const {
        assert(r <= n_);
        return product(r);
    }

    // return a[l] + a[l + 1] ... + a[r - 1]
    Value product(usize l, usize r) const {
        assert(l <= r and r <= n_);
        return Group::operation(Group::inverse(product(l)), product(r));
    }

    template <class Function>
    u32 maxRight(usize l, const Function& f) const {
        static_assert(std::is_convertible_v<decltype(f), std::function<bool(Value)>>, "maxRight's argument f must be function bool(T)");
        assert(l < n_);
        Value sum{ Group::inverse(product(l)) }; 
        u32 r{};
        for (u32 bit{ bitWidth_ } ; bit ; ) {
            bit--;
            u32 nxt{ r | (1u << bit) };
            if (nxt < dat_.size() and f(Group::operation(sum, dat_[nxt]))) {
                sum = Group::operation(sum, dat_[nxt]);
                r = std::move(nxt);
            }
        }
        assert(l <= r);
        return r;
    }

    template <class Function>
    u32 minLeft(usize r, const Function& f) const {
        static_assert(std::is_convertible_v<decltype(f), std::function<bool(Value)>>, "minLeft's argument f must be function bool(T)");
        assert(r <= n_);
        Value sum{ product(r) };
        u32 l{};
        for (u32 bit{ bitWidth_ } ; bit ; ) {
            bit--;
            u32 nxt{ l | (1u << bit) };
            if (nxt <= r and not f(Group::operation(Group::inverse(dat_[nxt]), sum))) {
                sum = Group::operation(Group::inverse(dat_[nxt]), sum);
                l = std::move(nxt);
            }
        }
        assert(l <= r);
        return l;
    }

    // debug print
    friend std::ostream& operator<<(std::ostream& os, const FenwickTree& ft) {
        for (u32 i{} ; i <= ft.size() ; i++) {
            os << ft.prefixProduct(i) << (i == ft.size() ? "" : " ");
        }
        return os;
    }

};


} // namespace zawa



namespace zawa {

template <class InputIterator>
u64 InversionNumber(InputIterator first, InputIterator last) {
    assert((usize)std::distance(first, last) >= usize{0});
    std::vector<std::remove_reference_t<decltype(*first)>> A(first, last);
    auto rec{[&](auto rec, usize L, usize R) -> u64 {
        if (R - L <= usize{1}) return 0; 
        usize M{(L + R) >> 1};
        u64 res{rec(rec, L, M) + rec(rec, M, R)};
        std::vector<u64> tmp(R - L);
        usize i{L}, j{M}, k{};
        while (i < M and j < R) {
            if (A[i] <= A[j]) {
                tmp[k++] = A[i++];
            }
            else {
                res += M - i;
                tmp[k++] = A[j++];
            }
        }
        while (i < M) tmp[k++] = A[i++];
        while (j < R) tmp[k++] = A[j++];
        for (usize l{L} ; l < R ; l++) {
            A[l] = tmp[l - L];
        }
        return res;
    }};
    return rec(rec, usize{0}, usize{A.size()});
}

template <class InputIterator>
bool InversionParity(InputIterator first, InputIterator last) {
    assert((usize)std::distance(first, last) >= usize{0});
    std::vector<std::remove_reference_t<decltype(*first)>> A(first, last);
    auto rec{[&](auto rec, usize L, usize R) -> bool {
        if (R - L <= usize{1}) return 0; 
        usize M{(L + R) >> 1};
        bool res{rec(rec, L, M) != rec(rec, M, R)};
        std::vector<u64> tmp(R - L);
        usize i{L}, j{M}, k{};
        while (i < M and j < R) {
            if (A[i] <= A[j]) {
                tmp[k++] = A[i++];
            }
            else {
                res ^= (M - i) & 1;
                tmp[k++] = A[j++];
            }
        }
        while (i < M) tmp[k++] = A[i++];
        while (j < R) tmp[k++] = A[j++];
        for (usize l{L} ; l < R ; l++) {
            A[l] = tmp[l - L];
        }
        return res;
    }};
    return rec(rec, usize{0}, usize{A.size()});
}

} // namespace zawa
using namespace zawa;

const int sq{2000};

int main() {
    std::cin.tie(nullptr)->sync_with_stdio(false);

    int N;
    std::cin >> N;
    std::vector<int> A(N);
    for (auto& a : A) std::cin >> a;
    int M;
    std::cin >> M;
    std::vector<int> B(M), E(M);
    for (int i{} ; i < M ; i++) {
        std::cin >> B[i] >> E[i];
        B[i]--; E[i]--;
    }
    const int sz{(N + sq - 1) / sq};
    std::vector<std::vector<int>> app(sz);
    for (int i{} ; i < N ; i++) {
        app[i / sq].push_back(A[i]);
    }
    {
        std::vector<int> tmp(A);
        for (int i{} ; i < M ; i++) {
            std::swap(tmp[B[i]], tmp[E[i]]);
            app[B[i] / sq].push_back(tmp[B[i]]);
            app[E[i] / sq].push_back(tmp[E[i]]);
        }
    }
    for (int i{} ; i < sz ; i++) {
        std::sort(app[i].begin(), app[i].end());
        app[i].erase(std::unique(app[i].begin(), app[i].end()), app[i].end());
    }
    std::vector<FenwickTree<AdditiveGroup<int>>> fen(sz);
    auto comp{[&](int i, int x) -> int {
        return (int)std::distance(app[i].begin(), std::lower_bound(app[i].begin(), app[i].end(), x));
    }};
    for (int i{} ; i < sz ; i++) {
        fen[i] = FenwickTree<AdditiveGroup<int>>(app[i].size());
        for (int j{i * sq} ; j < std::min(N, (i + 1) * sq) ; j++) {
            fen[i].operation(comp(i, A[j]), 1);
        }
    }
    // j = 0, 1, ..., i - 1について、x以上の値の数
    auto pref{[&](int i, int x) -> int {
        int pos{i / sq}, res{};
        for (int j{} ; j < pos ; j++) {
            res += fen[j].product(comp(j, x), app[j].size());
        }
        for (int j{pos * sq} ; j < i ; j++) {
            if (A[j] >= x) res++;
        }
        return res;
    }};
    // j = i + 1, i + 2, ..., N - 1について、x以上の値の数
    auto suf{[&](int i, int x) -> int {
        int pos{i / sq}, res{};
        for (int j{i + 1} ; j < std::min(N, (pos + 1) * sq) ; j++) {
            if (A[j] >= x) res++;
        }
        for (int j{pos + 1} ; j < sz ; j++) {
            res += fen[j].product(comp(j, x), app[j].size());
        }
        return res;
    }};
    long long inv{(long long)InversionNumber(A.begin(), A.end())};
    for (int i{} ; i < M ; i++) {
        int u{A[B[i]]}, v{A[E[i]]};
        // A[B[i]] <- v
        inv -= pref(B[i], A[B[i]] + 1);
        inv -= (N - B[i] - 1) - suf(B[i], A[B[i]]);
        fen[B[i] / sq].operation(comp(B[i] / sq, A[B[i]]), -1);
        fen[B[i] / sq].operation(comp(B[i] / sq, v), 1);
        A[B[i]] = v;
        inv += pref(B[i], A[B[i]] + 1);
        inv += (N - B[i] - 1) - suf(B[i], A[B[i]]);
        // A[E[i]] <- u
        inv -= pref(E[i], A[E[i]] + 1);
        inv -= (N - E[i] - 1) - suf(E[i], A[E[i]]);
        fen[E[i] / sq].operation(comp(E[i] / sq, A[E[i]]), -1);
        fen[E[i] / sq].operation(comp(E[i] / sq, u), 1);
        A[E[i]] = u;
        inv += pref(E[i], A[E[i]] + 1);
        inv += (N - E[i] - 1) - suf(E[i], A[E[i]]);
        std::cout << inv << '\n';
    }
}
accuracy: 1
time_ms: 2270
memory_kb: 21264
final_rank: 8

code_snippet: #pragma region Macros

// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,fma,abm,mmx,avx,avx2")

#include <bits/extc++.h>
// #include <atcoder/all>
// using namespace atcoder;
using namespace std;
using namespace __gnu_pbds;

// #include <boost/multiprecision/cpp_dec_float.hpp>
// #include <boost/multiprecision/cpp_int.hpp>
// namespace mp = boost::multiprecision;
// using Bint = mp::cpp_int;
// using Bdouble = mp::number<mp::cpp_dec_float<256>>;
// Bdouble Beps = 0.00000000000000000000000000000001; // 1e-32
// const bool equals(Bdouble a, Bdouble b) { return mp::fabs(a - b) < Beps; }

#define pb emplace_back
// #define int ll
#define endl '\n'
// #define unordered_map<int, int> gp_hash_table<int, int, custom_hash> 

#define sqrt __builtin_sqrtl
#define cbrt __builtin_cbrtl
#define hypot __builtin_hypotl

#define next asdnext
#define prev asdprev

using ll = long long;
using ld = long double;
const ld PI = acosl(-1);
const int INF = 1 << 30;
const ll INFL = 1LL << 61;
const int MOD = 998244353;
// const int MOD = 1000000007;

const ld EPS = 1e-10;
const bool equals(ld a, ld b) { return fabs((a) - (b)) < EPS; }

const vector<int> dx = {0, 1, 0, -1, 1, 1, -1, -1}; // → ↓ ← ↑ ↘ ↙ ↖ ↗
const vector<int> dy = {1, 0, -1, 0, 1, -1, -1, 1};

#define EC int
struct Edge {
    int from, to;
    EC cost;
    Edge() : from(-1), to(-1), cost(-1) {}
    Edge(int to, EC cost) : to(to), cost(cost) {}
    Edge(int from, int to, EC cost) : from(from), to(to), cost(cost) {}
    bool operator ==(const Edge& e) {
        return this->from == e.from && this->to == e.to && this->cost == e.cost;
    }
    bool operator !=(const Edge& e) {
        return this->from != e.from or this->to != e.to or this->cost != e.cost;
    }
};

chrono::system_clock::time_point start;
__attribute__((constructor))
void constructor() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(10);
    start = chrono::system_clock::now();
}

random_device seed_gen;
mt19937_64 rng(seed_gen());
uniform_int_distribution<int> dist_x(0, 1e9);
struct RNG {
    unsigned Int(unsigned l, unsigned r) {
        return dist_x(rng) % (r - l + 1) + l;
    }
    ld Double() {
        return ld(dist_x(rng)) / 1e9;
    }
} rnd;

using i64 = ll;
// using i64 = uint64_t;
// bit演算, x==0の場合は例外処理した方がよさそう. 区間は [l, r)
i64 lrmask(i64 l, i64 r) { return (1LL << r) - (1LL << l); }
i64 sub_bit(i64 x, i64 l, i64 r) { i64 b = x & ((1LL << r) - (1LL << l)); return b >> l; } // r溢れ可
i64 bit_width(i64 x) { return 64 - __builtin_clzll(x) + (x == 0); }

i64 popcount(i64 x) { return __builtin_popcountll(x); }
i64 popcount(i64 x, i64 l, i64 r) { return __builtin_popcountll(sub_bit(x, l, r)); }
i64 unpopcount(i64 x) { return bit_width(x) - __builtin_popcountll(x); }
i64 unpopcount(i64 x, i64 l, i64 r) { return r - l - __builtin_popcountll(sub_bit(x, l, r)); }
bool is_pow2(i64 x) { return __builtin_popcountll(x) == 1; } // xが負のときは常にfalse
bool is_pow4(i64 x) { return __builtin_popcount(x) == 1 && __builtin_ctz(x) % 2 == 0; }

i64 top_bit(i64 x) { return 63 - __builtin_clzll(x);} // 2^kの位 (x > 0)
i64 bot_bit(i64 x) { return __builtin_ctzll(x);} // 2^kの位 (x > 0)
// i64 next_bit(i64 x, i64 k) { return 0; }
// i64 prev_bit(i64 x, i64 k) { return 0; }
// i64 kth_bit(i64 x, i64 k) { return 0; }
i64 MSB(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // mask
i64 LSB(i64 x) { return (x & -x); } // mask

i64 countl_zero(i64 x) { return __builtin_clzll(x); }
i64 countl_one(i64 x) {
    i64 ret = 0, k = 63 - __builtin_clzll(x);
    while (k != -1 && (x & (1LL << k))) { k--; ret++; }
    return ret;
}
i64 countr_zero(i64 x) { return __builtin_ctzll(x); } // x==0のとき64が返ることに注意
i64 countr_one(i64 x) { i64 ret = 0; while (x & 1) { x >>= 1; ret++; } return ret; }

i64 floor_log2(i64 x) { if (x == 0) return 0; return 63 - __builtin_clzll(x); }
i64 bit_floor(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // MSBと同じ
i64 ceil_log2(i64 x) { if (x == 0) return 0; return 64 - __builtin_clzll(x - 1); }
i64 bit_ceil(i64 x) { if (x == 0) return 0; return 1LL << (64 - __builtin_clzll(x - 1)); }

i64 rotl(i64 x, i64 k) { // 有効bit内でrotate. オーバーフロー注意
    i64 w = bit_width(x); k %= w;
    return ((x << k) | (x >> (w - k))) & ((1LL << w) - 1);
}
// i64 rotl(i64 x, i64 l, i64 m, i64 r) {}
i64 rotr(i64 x, i64 k) {
    i64 w = bit_width(x); k %= w;
    return ((x >> k) | (x << (w - k))) & ((1LL << w) - 1);
}
// i64 rotr(i64 x, i64 l, i64 m, i64 r) {}
i64 bit_reverse(i64 x) { // 有効bit内で左右反転
    i64 r = 0, w = bit_width(x);
    for (i64 i = 0; i < w; i++) r |= ((x >> i) & 1) << (w - i - 1);
    return r;
}
// i64 bit_reverse(i64 x, i64 l, i64 r) { return 0; }

bool is_palindrome(i64 x) { return x == bit_reverse(x); }
bool is_palindrome(i64 x, i64 l, i64 r) { i64 b = sub_bit(x, l, r); return b == bit_reverse(b); }
i64 concat(i64 a, i64 b) { return (a << bit_width(b)) | b; } // オーバーフロー注意
i64 erase(i64 x, i64 l, i64 r) { return x>>r<<l | x&(1LL<<l - 1); } // [l, r) をカット

i64 hamming(i64 a, i64 b) { return __builtin_popcountll(a ^ b); }
i64 hamming(i64 a, i64 b, i64 l, i64 r) { return __builtin_popcountll(sub_bit(a, l, r) ^ sub_bit(b, l, r)); }
i64 compcount(i64 x) { return (__builtin_popcountll(x ^ (x >> 1)) + (x & 1)) / 2; }
i64 compcount2(i64 x) { return compcount(x & (x >> 1)); } // 長さ2以上の連結成分の個数
i64 adjacount(i64 x) { return __builtin_popcountll(x & (x >> 1)); } // 隣接する1のペアの個数

i64 next_combination(i64 x) {
    i64 t = x | (x - 1); return (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctzll(x) + 1));
}


__int128_t POW(__int128_t x, int n) {
    __int128_t ret = 1;
    assert(n >= 0);
    if (x == 1 or n == 0) ret = 1;
    else if (x == -1 && n % 2 == 0) ret = 1; 
    else if (x == -1) ret = -1; 
    else if (n % 2 == 0) {
        assert(x < INFL);
        ret = POW(x * x, n / 2);
    } else {
        assert(x < INFL);
        ret = x * POW(x, n - 1);
    }
    return ret;
}
int per(int x, int y) { // x = qy + r (0 <= r < y) を満たすq
    assert(y != 0);
    if (x >= 0 && y > 0) return x / y;
    if (x >= 0 && y < 0) return x / y - (x % y < 0);
    if (x < 0 && y < 0) return x / y + (x % y < 0);
    return x / y - (x % y < 0); //  (x < 0 && y > 0) 
}
int mod(int x, int y) { // x = qy + r (0 <= r < y) を満たすr
    assert(y != 0);
    if (x >= 0) return x % y;
    __int128_t ret = x % y; // (x < 0)
    ret += (__int128_t)abs(y) * INFL;
    ret %= abs(y);
    return ret;
}
int floor(int x, int y) { // (ld)x / y 以下の最大の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x >= 0 ? x / y : (x + 1) / y - 1;
}
int ceil(int x, int y) { // (ld)x / y 以上の最小の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x > 0 ? (x - 1) / y + 1 : x / y;
}
int round(int x, int y) {
    assert(y != 0);
    return (x * 2 + y) / (y * 2);
}
int round(int x, int y, int k) { // (ld)(x/y)を10^kの位に関して四捨五入
    assert(y != 0); // TODO
    return INF;
}
int round2(int x, int y) { // 五捨五超入 // 未verify
    assert(y != 0);
    if (y < 0) y = -y, x = -x;
    int z = z / y;
    if ((z * 2 + 1) * y <= y * 2) z++;
    return z;
}
// int round(ld x, int k) { // xを10^kの位に関して四捨五入
// }
// int floor(ld x, int k) { // xを10^kの位に関してflooring
// }
// int ceil(ld x, int k) { // xを10^kの位に関してceiling
// }
// int kth(int x, int y, int k) { // x / yの10^kの位の桁
// }
int floor(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return floor(x / y);
    // floor(x) = ceil(x - 1) という話も
}
int ceil(ld x, ld y) { // 誤差対策TODO // ceil(p/q) = -floor(-(p/q))らしい
    assert(!equals(y, 0));
    return ceil(x / y);
    // ceil(x) = floor(x + 1)
}
int perl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす q
    // 未verify. 誤差対策TODO. EPS外してもいいかも。
    assert(!equals(y, 0));
    if (x >= 0 && y > 0) return floor(x / y)+EPS;
    if (x >= 0 && y < 0) return -floor(x / fabs(y));
    if (x < 0 && y < 0) return floor(x / y) + (x - floor(x/y)*y < -EPS);
    return floor(x / y) - (x - floor(x/y)*y < -EPS); //  (x < 0 && y > 0) 
}
ld modl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす r
    // 未verify. 誤差対策TODO. -0.0が返りうる。
    assert(!equals(y, 0));
    if (x >= 0) return x - fabs(y)*fabs(per(x, y));
    return x - fabs(y)*floor(x, fabs(y));
}
int seisuu(ld x) { return (int)x; } // 整数部分. 誤差対策TODO
int modf(ld x) {
	if (x < 0) return ceill(x);
	else return floorl(x);
}
// 正なら+EPS, 負なら-EPSしてから、文字列に直して小数点以下を捨てる?
int seisuu(int x, int y) {
    assert(y != 0);
    return x / y;
}
int seisuu(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return (int)(x / y);
}

template <class T> pair<T, T> max(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first > b.first or a.first == b.first && a.second > b.second) return a;
    return b;
}
template <class T> pair<T, T> min(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first < b.first or a.first == b.first && a.second < b.second) return a;
    return b;
}

template <class T> bool chmax(T &a, const T& b) {
    if (a < b) { a = b; return true; } return false;
}
template <class T> bool chmin(T &a, const T& b) {
    if (a > b) { a = b; return true; } return false;
}
template <class T> T mid(T a, T b, T c) { // 誤差対策TODO
    return a + b + c - max({a, b, c}) - min({a, b, c});
}
template <class T> void Sort(T &a, T &b, bool rev = false) { 
    if (rev == false) {  // TODO テンプレート引数
        if (a > b) swap(a, b);
    } else {
        if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c); if (b > c) swap(b, c);
    } else {
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, T &d, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c);  if (a > d) swap(a, d);
        if (b > c) swap(b, c); if (b > d) swap(b, d); if (c > d) swap(c, d);
    } else {
        if (d > c) swap(d, c); if (d > b) swap(d, b); if (d > a) swap(d, a);
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

class Compress {
public:
    int sz = 0;
    // gp_hash_table<int, int, custom_hash> Z, UZ;
    unordered_map<int, int> Z;    // 元の値 -> 圧縮した値
    unordered_map<int, int> UZ;   // 圧縮した値 -> 元の値

    Compress(const vector<int> &V, int base = 0) {
        this->sz = base;
        set<int> s(V.begin(), V.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }
    
    Compress(const vector<int> &V1, const vector<int> &V2, int base = 0) {
        this->sz = base;
        vector<int> V3 = V2;
        V3.insert(V3.end(), V1.begin(), V1.end());
        set<int> s(V3.begin(), V3.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2, const vector<int> &V3, int base = 0) {
        this->sz = base;
        vector<int> V4 = V1;
        V4.insert(V4.end(), V2.begin(), V2.end());
        V4.insert(V4.end(), V3.begin(), V3.end());
        set<int> s(V4.begin(), V4.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2,
            const vector<int> &V3, const vector<int> &V4, int base = 0) {
        this->sz = base;
        vector<int> V5 = V1;
        V5.insert(V5.end(), V2.begin(), V2.end());
        V5.insert(V5.end(), V3.begin(), V3.end());
        V5.insert(V5.end(), V4.begin(), V4.end());
        set<int> s(V5.begin(), V5.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    vector<int> zip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = Z[ret[i]];
        }
        return ret;
    }

    vector<int> unzip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = UZ[ret[i]];
        }
        return ret;
    }

    int size() { return sz; }

    int encode(int x) { return Z[x]; }
    int decode(int x) {
        if (UZ.find(x) == UZ.end()) return -1; // xが元の配列に存在しないとき
        return UZ[x];
    }
};

class UnionFind {
public:
	UnionFind() = default;
    UnionFind(int N) : par(N), sz(N, 1) {
        iota(par.begin(), par.end(), 0);
    }
	int root(int x) {
		if (par[x] == x) return x;
		return (par[x] = root(par[x]));
	}
	bool unite(int x, int y) {
		int rx = root(x);
		int ry = root(y);
        if (rx == ry) return false;
		if (sz[rx] < sz[ry]) swap(rx, ry);
		sz[rx] += sz[ry];
		par[ry] = rx;
        return true;
	}
	bool issame(int x, int y) { return (root(x) == root(y)); }
	int size(int x) { return sz[root(x)]; }
    vector<vector<int>> groups(int N) {
        vector<vector<int>> G(N);
        for (int x = 0; x < N; x++) {
            G[root(x)].push_back(x);
        }
		G.erase( remove_if(G.begin(), G.end(),
            [&](const vector<int>& V) { return V.empty(); }), G.end());
        return G;
    }
private:
	vector<int> par, sz;
};

template<typename T>
struct BIT {
    int N;             // 要素数
    vector<T> bit[2];  // データの格納先
    BIT(int N_, int x = 0) {
        N = N_ + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        if (x != 0) {
            for (int i = 0; i < N; i++) add(i, x);
        }
    }
    BIT(const vector<int> &A) {
        N = A.size() + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        for (int i = 0; i < (int)A.size(); i++) add(i, A[i]);
    }
    void add_sub(int p, int i, T x) {
        while (i < N) { bit[p][i] += x; i += (i & -i); }
    }
    void add(int l, int r, T x) {
        add_sub(0, l + 1, -x * l); add_sub(0, r + 1, x * r);
        add_sub(1, l + 1, x); add_sub(1, r + 1, -x);
    }
    void add(int i, T x) { add(i, i + 1, x); }
    T sum_sub(int p, int i) {
        T ret = 0;
        while (i > 0) { ret += bit[p][i]; i -= (i & -i); }
        return ret;
    }
    T sum(int i) { return sum_sub(0, i) + sum_sub(1, i) * i; }
    T sum(int l, int r) { return sum(r) - sum(l); }
    T get(int i) { return sum(i, i + 1); }
    void set(int i, T x) { T s = get(i); add(i, -s + x); }
};

#pragma endregion

// #define pb emplace_back
// using ll = long long;
// const int INF = 1 << 30;
// const ll INFL = 1LL << 61;

const int Nmax = 500003, Qmax = 30007, NQmax = 530011, V = 25000030;

int N, Q, A[Nmax], B[NQmax], sz; // 座圧列と座圧後のサイズ？

struct qry {
    int t, l, r, x, k;
} query[Qmax];

int v(int x) {
    return lower_bound(B + 1, B + sz + 1, x) - B;
}

void disc(int N, int Q) { // 座圧
    memcpy(B, A, sizeof A);

    // for (int i = 0; i < Q; i++) {
    //     if (query[i].t != 2) B[++N] = query[i].x;
    // }

    sort(B + 1, B + N + 1);
    sz = unique(B + 1, B + N + 1) - B - 1;
    B[0] = -INF - 1, B[sz + 1] = INF + 1;
}

vector<int> rt(NQmax), xl(NQmax), xr(NQmax);
int vl, vr;
class LOJ {
    class seg {
        int c;

        struct node {
            int l, r, x;
        } a[V];

        void up(int x) {
            a[x].x = a[a[x].l].x + a[a[x].r].x;
        }

    public:

        void add(int p, int x, int &X, int l = 1, int r = sz) {
            a[++c] = a[X], X = c;

            if (l == r) {
                a[X].x += x;
                return;
            }

            int m = l + r >> 1;
            p <= m ? add(p, x, a[X].l, l, m) : add(p, x, a[X].r, m + 1, r);
            up(X);
        }

        int rank(int x, int l = 1, int r = sz) {
            if (l == r) return 1;

            int m = l + r >> 1;

            if (x <= m) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return rank(x, l, m);
            } else {
                int t = 0;

                for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x, xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x, xr[i] = a[xr[i]].r;

                return t + rank(x, m + 1, r);
            }
        }

        int kth_smallest(int x, int l = 1, int r = sz) {
            if (l == r)
                return l;

            int m = l + r >> 1, t = 0;

            for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x;
            for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x;

            if (x <= t) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return kth_smallest(x, l, m);
            } else {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].r;

                return kth_smallest(x - t, m + 1, r);
            }
        }
    } s;

public:

    void add(int p1, int p2, int x) {
        for (int i = p1; i <= N; i += i & -i) s.add(p2, x, rt[i]);
    }

    void _X(int l, int r) {
        vl = vr = 0;

        for (int i = l - 1; i > 0; i &= i - 1) xl[++vl] = rt[i];

        for (int i = r; i > 0; i &= i - 1) xr[++vr] = rt[i];
    }

    int rank(int l, int r, int x) {
        _X(l, r);
        return s.rank(x);
    }

    int count(int l, int r, int x) { // 未verify
        return rank(l, r, x + 1) - rank(l, r, x);
    }

    int count(int l, int r, int a, int b) { // 未verify
        return rank(l, r, b) - rank(l, r, a);
    }

    int kth_smallest(int l, int r, int k) {
        // assert(0 <= k && k < r - l);
        _X(l, r);
        return s.kth_smallest(k);
    }

    int kth_largest(int l, int r, int k) { // 未verify
        return kth_smallest(l, r, r - l - k - 1);
    }

    // int get(int i) {
    //     return kth_smallest(i, i + 1, 0);
    //     return ;
    // }

    int prev_value(int l, int r, int x) {
        int t = rank(l, r, x) - 1;
        return t ? kth_smallest(l, r, t) : 0;
    }

    int next_value(int l, int r, int x) {
        int t = rank(l, r, x + 1);
        return t <= r - l + 1 ? kth_smallest(l, r, t) : sz + 1;
    }
} seg;

signed main() {
    cin >> N;

    // Aの入力は1-indexed
    for (int i = 1; i <= N; i++) cin >> A[i];

    cin >> Q;

    // 区間は1-indexの閉区間
    for (int i = 0; i < Q; i++) {
        cin >> query[i].l >> query[i].r;
    }

    disc(N, Q);

    for (int i = 1; i <= N; i++) seg.add(i, v(A[i]), 1);

    tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> tr;
    int t = 0; // 初めの転倒数
    for (int i = N; i >= 1; i--) {
        tr.insert(A[i]);
        // A[i]未満の個数を逆順に加算していく
        t += tr.order_of_key(A[i]);
    }

    for (int i = 0; i < Q; i++) {
        t -= seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t -= seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        t -= seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        int temp = A[query[i].l];

        seg.add(query[i].l, v(A[query[i].l]), -1);
        A[query[i].l] = A[query[i].r];
        seg.add(query[i].l, v(A[query[i].l]), 1);

        seg.add(query[i].r, v(A[query[i].r]), -1);
        A[query[i].r] = temp;
        seg.add(query[i].r, v(A[query[i].r]), 1);

        t += seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        t += seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t += seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        cout << t << endl;
    }
}
accuracy: 0.7
time_ms: 80
memory_kb: 81752
final_rank: 10

code_snippet: #pragma region Macros

// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,fma,abm,mmx,avx,avx2")

#include <bits/extc++.h>
// #include <atcoder/all>
// using namespace atcoder;
using namespace std;
using namespace __gnu_pbds;

// #include <boost/multiprecision/cpp_dec_float.hpp>
// #include <boost/multiprecision/cpp_int.hpp>
// namespace mp = boost::multiprecision;
// using Bint = mp::cpp_int;
// using Bdouble = mp::number<mp::cpp_dec_float<256>>;
// Bdouble Beps = 0.00000000000000000000000000000001; // 1e-32
// const bool equals(Bdouble a, Bdouble b) { return mp::fabs(a - b) < Beps; }

#define pb emplace_back
#define int ll
#define endl '\n'
// #define unordered_map<int, int> gp_hash_table<int, int, custom_hash> 

#define sqrt __builtin_sqrtl
#define cbrt __builtin_cbrtl
#define hypot __builtin_hypotl

#define next asdnext
#define prev asdprev

using ll = long long;
using ld = long double;
const ld PI = acosl(-1);
const int INF = 1 << 30;
const ll INFL = 1LL << 61;
const int MOD = 998244353;
// const int MOD = 1000000007;

const ld EPS = 1e-10;
const bool equals(ld a, ld b) { return fabs((a) - (b)) < EPS; }

const vector<int> dx = {0, 1, 0, -1, 1, 1, -1, -1}; // → ↓ ← ↑ ↘ ↙ ↖ ↗
const vector<int> dy = {1, 0, -1, 0, 1, -1, -1, 1};

#define EC int
struct Edge {
    int from, to;
    EC cost;
    Edge() : from(-1), to(-1), cost(-1) {}
    Edge(int to, EC cost) : to(to), cost(cost) {}
    Edge(int from, int to, EC cost) : from(from), to(to), cost(cost) {}
    bool operator ==(const Edge& e) {
        return this->from == e.from && this->to == e.to && this->cost == e.cost;
    }
    bool operator !=(const Edge& e) {
        return this->from != e.from or this->to != e.to or this->cost != e.cost;
    }
};

chrono::system_clock::time_point start;
__attribute__((constructor))
void constructor() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(10);
    start = chrono::system_clock::now();
}

random_device seed_gen;
mt19937_64 rng(seed_gen());
uniform_int_distribution<int> dist_x(0, 1e9);
struct RNG {
    unsigned Int(unsigned l, unsigned r) {
        return dist_x(rng) % (r - l + 1) + l;
    }
    ld Double() {
        return ld(dist_x(rng)) / 1e9;
    }
} rnd;

using i64 = ll;
// using i64 = uint64_t;
// bit演算, x==0の場合は例外処理した方がよさそう. 区間は [l, r)
i64 lrmask(i64 l, i64 r) { return (1LL << r) - (1LL << l); }
i64 sub_bit(i64 x, i64 l, i64 r) { i64 b = x & ((1LL << r) - (1LL << l)); return b >> l; } // r溢れ可
i64 bit_width(i64 x) { return 64 - __builtin_clzll(x) + (x == 0); }

i64 popcount(i64 x) { return __builtin_popcountll(x); }
i64 popcount(i64 x, i64 l, i64 r) { return __builtin_popcountll(sub_bit(x, l, r)); }
i64 unpopcount(i64 x) { return bit_width(x) - __builtin_popcountll(x); }
i64 unpopcount(i64 x, i64 l, i64 r) { return r - l - __builtin_popcountll(sub_bit(x, l, r)); }
bool is_pow2(i64 x) { return __builtin_popcountll(x) == 1; } // xが負のときは常にfalse
bool is_pow4(i64 x) { return __builtin_popcount(x) == 1 && __builtin_ctz(x) % 2 == 0; }

i64 top_bit(i64 x) { return 63 - __builtin_clzll(x);} // 2^kの位 (x > 0)
i64 bot_bit(i64 x) { return __builtin_ctzll(x);} // 2^kの位 (x > 0)
// i64 next_bit(i64 x, i64 k) { return 0; }
// i64 prev_bit(i64 x, i64 k) { return 0; }
// i64 kth_bit(i64 x, i64 k) { return 0; }
i64 MSB(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // mask
i64 LSB(i64 x) { return (x & -x); } // mask

i64 countl_zero(i64 x) { return __builtin_clzll(x); }
i64 countl_one(i64 x) {
    i64 ret = 0, k = 63 - __builtin_clzll(x);
    while (k != -1 && (x & (1LL << k))) { k--; ret++; }
    return ret;
}
i64 countr_zero(i64 x) { return __builtin_ctzll(x); } // x==0のとき64が返ることに注意
i64 countr_one(i64 x) { i64 ret = 0; while (x & 1) { x >>= 1; ret++; } return ret; }

i64 floor_log2(i64 x) { if (x == 0) return 0; return 63 - __builtin_clzll(x); }
i64 bit_floor(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // MSBと同じ
i64 ceil_log2(i64 x) { if (x == 0) return 0; return 64 - __builtin_clzll(x - 1); }
i64 bit_ceil(i64 x) { if (x == 0) return 0; return 1LL << (64 - __builtin_clzll(x - 1)); }

i64 rotl(i64 x, i64 k) { // 有効bit内でrotate. オーバーフロー注意
    i64 w = bit_width(x); k %= w;
    return ((x << k) | (x >> (w - k))) & ((1LL << w) - 1);
}
// i64 rotl(i64 x, i64 l, i64 m, i64 r) {}
i64 rotr(i64 x, i64 k) {
    i64 w = bit_width(x); k %= w;
    return ((x >> k) | (x << (w - k))) & ((1LL << w) - 1);
}
// i64 rotr(i64 x, i64 l, i64 m, i64 r) {}
i64 bit_reverse(i64 x) { // 有効bit内で左右反転
    i64 r = 0, w = bit_width(x);
    for (i64 i = 0; i < w; i++) r |= ((x >> i) & 1) << (w - i - 1);
    return r;
}
// i64 bit_reverse(i64 x, i64 l, i64 r) { return 0; }

bool is_palindrome(i64 x) { return x == bit_reverse(x); }
bool is_palindrome(i64 x, i64 l, i64 r) { i64 b = sub_bit(x, l, r); return b == bit_reverse(b); }
i64 concat(i64 a, i64 b) { return (a << bit_width(b)) | b; } // オーバーフロー注意
i64 erase(i64 x, i64 l, i64 r) { return x>>r<<l | x&(1LL<<l - 1); } // [l, r) をカット

i64 hamming(i64 a, i64 b) { return __builtin_popcountll(a ^ b); }
i64 hamming(i64 a, i64 b, i64 l, i64 r) { return __builtin_popcountll(sub_bit(a, l, r) ^ sub_bit(b, l, r)); }
i64 compcount(i64 x) { return (__builtin_popcountll(x ^ (x >> 1)) + (x & 1)) / 2; }
i64 compcount2(i64 x) { return compcount(x & (x >> 1)); } // 長さ2以上の連結成分の個数
i64 adjacount(i64 x) { return __builtin_popcountll(x & (x >> 1)); } // 隣接する1のペアの個数

i64 next_combination(i64 x) {
    i64 t = x | (x - 1); return (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctzll(x) + 1));
}


__int128_t POW(__int128_t x, int n) {
    __int128_t ret = 1;
    assert(n >= 0);
    if (x == 1 or n == 0) ret = 1;
    else if (x == -1 && n % 2 == 0) ret = 1; 
    else if (x == -1) ret = -1; 
    else if (n % 2 == 0) {
        assert(x < INFL);
        ret = POW(x * x, n / 2);
    } else {
        assert(x < INFL);
        ret = x * POW(x, n - 1);
    }
    return ret;
}
int per(int x, int y) { // x = qy + r (0 <= r < y) を満たすq
    assert(y != 0);
    if (x >= 0 && y > 0) return x / y;
    if (x >= 0 && y < 0) return x / y - (x % y < 0);
    if (x < 0 && y < 0) return x / y + (x % y < 0);
    return x / y - (x % y < 0); //  (x < 0 && y > 0) 
}
int mod(int x, int y) { // x = qy + r (0 <= r < y) を満たすr
    assert(y != 0);
    if (x >= 0) return x % y;
    __int128_t ret = x % y; // (x < 0)
    ret += (__int128_t)abs(y) * INFL;
    ret %= abs(y);
    return ret;
}
int floor(int x, int y) { // (ld)x / y 以下の最大の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x >= 0 ? x / y : (x + 1) / y - 1;
}
int ceil(int x, int y) { // (ld)x / y 以上の最小の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x > 0 ? (x - 1) / y + 1 : x / y;
}
int round(int x, int y) {
    assert(y != 0);
    return (x * 2 + y) / (y * 2);
}
int round(int x, int y, int k) { // (ld)(x/y)を10^kの位に関して四捨五入
    assert(y != 0); // TODO
    return INF;
}
int round2(int x, int y) { // 五捨五超入 // 未verify
    assert(y != 0);
    if (y < 0) y = -y, x = -x;
    int z = z / y;
    if ((z * 2 + 1) * y <= y * 2) z++;
    return z;
}
// int round(ld x, int k) { // xを10^kの位に関して四捨五入
// }
// int floor(ld x, int k) { // xを10^kの位に関してflooring
// }
// int ceil(ld x, int k) { // xを10^kの位に関してceiling
// }
// int kth(int x, int y, int k) { // x / yの10^kの位の桁
// }
int floor(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return floor(x / y);
    // floor(x) = ceil(x - 1) という話も
}
int ceil(ld x, ld y) { // 誤差対策TODO // ceil(p/q) = -floor(-(p/q))らしい
    assert(!equals(y, 0));
    return ceil(x / y);
    // ceil(x) = floor(x + 1)
}
int perl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす q
    // 未verify. 誤差対策TODO. EPS外してもいいかも。
    assert(!equals(y, 0));
    if (x >= 0 && y > 0) return floor(x / y)+EPS;
    if (x >= 0 && y < 0) return -floor(x / fabs(y));
    if (x < 0 && y < 0) return floor(x / y) + (x - floor(x/y)*y < -EPS);
    return floor(x / y) - (x - floor(x/y)*y < -EPS); //  (x < 0 && y > 0) 
}
ld modl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす r
    // 未verify. 誤差対策TODO. -0.0が返りうる。
    assert(!equals(y, 0));
    if (x >= 0) return x - fabs(y)*fabs(per(x, y));
    return x - fabs(y)*floor(x, fabs(y));
}
int seisuu(ld x) { return (int)x; } // 整数部分. 誤差対策TODO
int modf(ld x) {
	if (x < 0) return ceill(x);
	else return floorl(x);
}
// 正なら+EPS, 負なら-EPSしてから、文字列に直して小数点以下を捨てる?
int seisuu(int x, int y) {
    assert(y != 0);
    return x / y;
}
int seisuu(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return (int)(x / y);
}

template <class T> pair<T, T> max(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first > b.first or a.first == b.first && a.second > b.second) return a;
    return b;
}
template <class T> pair<T, T> min(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first < b.first or a.first == b.first && a.second < b.second) return a;
    return b;
}

template <class T> bool chmax(T &a, const T& b) {
    if (a < b) { a = b; return true; } return false;
}
template <class T> bool chmin(T &a, const T& b) {
    if (a > b) { a = b; return true; } return false;
}
template <class T> T mid(T a, T b, T c) { // 誤差対策TODO
    return a + b + c - max({a, b, c}) - min({a, b, c});
}
template <class T> void Sort(T &a, T &b, bool rev = false) { 
    if (rev == false) {  // TODO テンプレート引数
        if (a > b) swap(a, b);
    } else {
        if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c); if (b > c) swap(b, c);
    } else {
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, T &d, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c);  if (a > d) swap(a, d);
        if (b > c) swap(b, c); if (b > d) swap(b, d); if (c > d) swap(c, d);
    } else {
        if (d > c) swap(d, c); if (d > b) swap(d, b); if (d > a) swap(d, a);
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

class Compress {
public:
    int sz = 0;
    // gp_hash_table<int, int, custom_hash> Z, UZ;
    unordered_map<int, int> Z;    // 元の値 -> 圧縮した値
    unordered_map<int, int> UZ;   // 圧縮した値 -> 元の値

    Compress(const vector<int> &V, int base = 0) {
        this->sz = base;
        set<int> s(V.begin(), V.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }
    
    Compress(const vector<int> &V1, const vector<int> &V2, int base = 0) {
        this->sz = base;
        vector<int> V3 = V2;
        V3.insert(V3.end(), V1.begin(), V1.end());
        set<int> s(V3.begin(), V3.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2, const vector<int> &V3, int base = 0) {
        this->sz = base;
        vector<int> V4 = V1;
        V4.insert(V4.end(), V2.begin(), V2.end());
        V4.insert(V4.end(), V3.begin(), V3.end());
        set<int> s(V4.begin(), V4.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2,
            const vector<int> &V3, const vector<int> &V4, int base = 0) {
        this->sz = base;
        vector<int> V5 = V1;
        V5.insert(V5.end(), V2.begin(), V2.end());
        V5.insert(V5.end(), V3.begin(), V3.end());
        V5.insert(V5.end(), V4.begin(), V4.end());
        set<int> s(V5.begin(), V5.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    vector<int> zip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = Z[ret[i]];
        }
        return ret;
    }

    vector<int> unzip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = UZ[ret[i]];
        }
        return ret;
    }

    int size() { return sz; }

    int encode(int x) { return Z[x]; }
    int decode(int x) {
        if (UZ.find(x) == UZ.end()) return -1; // xが元の配列に存在しないとき
        return UZ[x];
    }
};

class UnionFind {
public:
	UnionFind() = default;
    UnionFind(int N) : par(N), sz(N, 1) {
        iota(par.begin(), par.end(), 0);
    }
	int root(int x) {
		if (par[x] == x) return x;
		return (par[x] = root(par[x]));
	}
	bool unite(int x, int y) {
		int rx = root(x);
		int ry = root(y);
        if (rx == ry) return false;
		if (sz[rx] < sz[ry]) swap(rx, ry);
		sz[rx] += sz[ry];
		par[ry] = rx;
        return true;
	}
	bool issame(int x, int y) { return (root(x) == root(y)); }
	int size(int x) { return sz[root(x)]; }
    vector<vector<int>> groups(int N) {
        vector<vector<int>> G(N);
        for (int x = 0; x < N; x++) {
            G[root(x)].push_back(x);
        }
		G.erase( remove_if(G.begin(), G.end(),
            [&](const vector<int>& V) { return V.empty(); }), G.end());
        return G;
    }
private:
	vector<int> par, sz;
};

template<typename T>
struct BIT {
    int N;             // 要素数
    vector<T> bit[2];  // データの格納先
    BIT(int N_, int x = 0) {
        N = N_ + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        if (x != 0) {
            for (int i = 0; i < N; i++) add(i, x);
        }
    }
    BIT(const vector<int> &A) {
        N = A.size() + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        for (int i = 0; i < (int)A.size(); i++) add(i, A[i]);
    }
    void add_sub(int p, int i, T x) {
        while (i < N) { bit[p][i] += x; i += (i & -i); }
    }
    void add(int l, int r, T x) {
        add_sub(0, l + 1, -x * l); add_sub(0, r + 1, x * r);
        add_sub(1, l + 1, x); add_sub(1, r + 1, -x);
    }
    void add(int i, T x) { add(i, i + 1, x); }
    T sum_sub(int p, int i) {
        T ret = 0;
        while (i > 0) { ret += bit[p][i]; i -= (i & -i); }
        return ret;
    }
    T sum(int i) { return sum_sub(0, i) + sum_sub(1, i) * i; }
    T sum(int l, int r) { return sum(r) - sum(l); }
    T get(int i) { return sum(i, i + 1); }
    void set(int i, T x) { T s = get(i); add(i, -s + x); }
};

#pragma endregion

// #define pb emplace_back
// using ll = long long;
// const int INF = 1 << 30;
// const ll INFL = 1LL << 61;

const int Nmax = 500003, Qmax = 30007, NQmax = 530011, V = 25000030;

int N, Q, A[Nmax], B[NQmax], sz; // 座圧列と座圧後のサイズ？

struct qry {
    int t, l, r, x, k;
} query[Qmax];

int v(int x) {
    return lower_bound(B + 1, B + sz + 1, x) - B;
}

void disc(int N, int Q) { // 座圧
    memcpy(B, A, sizeof A);

    // for (int i = 0; i < Q; i++) {
    //     if (query[i].t != 2) B[++N] = query[i].x;
    // }

    sort(B + 1, B + N + 1);
    sz = unique(B + 1, B + N + 1) - B - 1;
    B[0] = -INF, B[sz + 1] = INF;
}

vector<int> rt(NQmax), xl(NQmax), xr(NQmax);
int vl, vr;
class LOJ {
    class seg {
        int c;

        struct node {
            int l, r, x;
        } a[V];

        void up(int x) {
            a[x].x = a[a[x].l].x + a[a[x].r].x;
        }

    public:

        void add(int p, int x, int &X, int l = 1, int r = sz) {
            a[++c] = a[X], X = c;

            if (l == r) {
                a[X].x += x;
                return;
            }

            int m = l + r >> 1;
            p <= m ? add(p, x, a[X].l, l, m) : add(p, x, a[X].r, m + 1, r);
            up(X);
        }

        int rank(int x, int l = 1, int r = sz) {
            if (l == r) return 1;

            int m = l + r >> 1;

            if (x <= m) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return rank(x, l, m);
            } else {
                int t = 0;

                for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x, xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x, xr[i] = a[xr[i]].r;

                return t + rank(x, m + 1, r);
            }
        }

        int kth_smallest(int x, int l = 1, int r = sz) {
            if (l == r)
                return l;

            int m = l + r >> 1, t = 0;

            for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x;
            for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x;

            if (x <= t) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return kth_smallest(x, l, m);
            } else {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].r;

                return kth_smallest(x - t, m + 1, r);
            }
        }
    } s;

public:

    void add(int p1, int p2, int x) {
        for (int i = p1; i <= N; i += i & -i) s.add(p2, x, rt[i]);
    }

    void _X(int l, int r) {
        vl = vr = 0;

        for (int i = l - 1; i > 0; i &= i - 1) xl[++vl] = rt[i];

        for (int i = r; i > 0; i &= i - 1) xr[++vr] = rt[i];
    }

    int rank(int l, int r, int x) {
        _X(l, r);
        return s.rank(x);
    }

    int count(int l, int r, int x) { // 未verify
        return rank(l, r, x + 1) - rank(l, r, x);
    }

    int count(int l, int r, int a, int b) { // 未verify
        return rank(l, r, b) - rank(l, r, a);
    }

    int kth_smallest(int l, int r, int k) {
        // assert(0 <= k && k < r - l);
        _X(l, r);
        return s.kth_smallest(k);
    }

    int kth_largest(int l, int r, int k) { // 未verify
        return kth_smallest(l, r, r - l - k - 1);
    }

    // int get(int i) {
    //     return kth_smallest(i, i + 1, 0);
    //     return ;
    // }

    int prev_value(int l, int r, int x) {
        int t = rank(l, r, x) - 1;
        return t ? kth_smallest(l, r, t) : 0;
    }

    int next_value(int l, int r, int x) {
        int t = rank(l, r, x + 1);
        return t <= r - l + 1 ? kth_smallest(l, r, t) : sz + 1;
    }
} seg;

signed main() {
    cin >> N;

    // Aの入力は1-indexed
    for (int i = 1; i <= N; i++) cin >> A[i];

    cin >> Q;

    // 区間は1-indexの閉区間
    for (int i = 0; i < Q; i++) {
        cin >> query[i].l >> query[i].r;
    }

    disc(N, Q);

    for (int i = 1; i <= N; i++) seg.add(i, v(A[i]), 1);

    tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> tr;
    int t = 0; // 初めの転倒数
    for (int i = N; i >= 1; i--) {
        tr.insert(A[i]);
        // A[i]未満の個数を逆順に加算していく
        t += tr.order_of_key(A[i]);
    }

    for (int i = 0; i < Q; i++) {
        t -= seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t -= seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        t -= seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        int temp = A[query[i].l];

        seg.add(query[i].l, v(A[query[i].l]), -1);
        A[query[i].l] = A[query[i].r];
        seg.add(query[i].l, v(A[query[i].l]), 1);

        seg.add(query[i].r, v(A[query[i].r]), -1);
        A[query[i].r] = temp;
        seg.add(query[i].r, v(A[query[i].r]), 1);

        t += seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        t += seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t += seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        cout << t << endl;
    }
}
accuracy: 0.7
time_ms: 100
memory_kb: 155664
final_rank: 14

code_snippet: #pragma region Macros

// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,fma,abm,mmx,avx,avx2")

#include <bits/extc++.h>
// #include <atcoder/all>
// using namespace atcoder;
using namespace std;
using namespace __gnu_pbds;

// #include <boost/multiprecision/cpp_dec_float.hpp>
// #include <boost/multiprecision/cpp_int.hpp>
// namespace mp = boost::multiprecision;
// using Bint = mp::cpp_int;
// using Bdouble = mp::number<mp::cpp_dec_float<256>>;
// Bdouble Beps = 0.00000000000000000000000000000001; // 1e-32
// const bool equals(Bdouble a, Bdouble b) { return mp::fabs(a - b) < Beps; }

#define pb emplace_back
#define int ll
#define endl '\n'
// #define unordered_map<int, int> gp_hash_table<int, int, custom_hash> 

#define sqrt __builtin_sqrtl
#define cbrt __builtin_cbrtl
#define hypot __builtin_hypotl

#define next asdnext
#define prev asdprev

using ll = long long;
using ld = long double;
const ld PI = acosl(-1);
const int INF = 1 << 30;
const ll INFL = 1LL << 61;
const int MOD = 998244353;
// const int MOD = 1000000007;

const ld EPS = 1e-10;
const bool equals(ld a, ld b) { return fabs((a) - (b)) < EPS; }

const vector<int> dx = {0, 1, 0, -1, 1, 1, -1, -1}; // → ↓ ← ↑ ↘ ↙ ↖ ↗
const vector<int> dy = {1, 0, -1, 0, 1, -1, -1, 1};

#define EC int
struct Edge {
    int from, to;
    EC cost;
    Edge() : from(-1), to(-1), cost(-1) {}
    Edge(int to, EC cost) : to(to), cost(cost) {}
    Edge(int from, int to, EC cost) : from(from), to(to), cost(cost) {}
    bool operator ==(const Edge& e) {
        return this->from == e.from && this->to == e.to && this->cost == e.cost;
    }
    bool operator !=(const Edge& e) {
        return this->from != e.from or this->to != e.to or this->cost != e.cost;
    }
};

chrono::system_clock::time_point start;
__attribute__((constructor))
void constructor() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(10);
    start = chrono::system_clock::now();
}

random_device seed_gen;
mt19937_64 rng(seed_gen());
uniform_int_distribution<int> dist_x(0, 1e9);
struct RNG {
    unsigned Int(unsigned l, unsigned r) {
        return dist_x(rng) % (r - l + 1) + l;
    }
    ld Double() {
        return ld(dist_x(rng)) / 1e9;
    }
} rnd;

using i64 = ll;
// using i64 = uint64_t;
// bit演算, x==0の場合は例外処理した方がよさそう. 区間は [l, r)
i64 lrmask(i64 l, i64 r) { return (1LL << r) - (1LL << l); }
i64 sub_bit(i64 x, i64 l, i64 r) { i64 b = x & ((1LL << r) - (1LL << l)); return b >> l; } // r溢れ可
i64 bit_width(i64 x) { return 64 - __builtin_clzll(x) + (x == 0); }

i64 popcount(i64 x) { return __builtin_popcountll(x); }
i64 popcount(i64 x, i64 l, i64 r) { return __builtin_popcountll(sub_bit(x, l, r)); }
i64 unpopcount(i64 x) { return bit_width(x) - __builtin_popcountll(x); }
i64 unpopcount(i64 x, i64 l, i64 r) { return r - l - __builtin_popcountll(sub_bit(x, l, r)); }
bool is_pow2(i64 x) { return __builtin_popcountll(x) == 1; } // xが負のときは常にfalse
bool is_pow4(i64 x) { return __builtin_popcount(x) == 1 && __builtin_ctz(x) % 2 == 0; }

i64 top_bit(i64 x) { return 63 - __builtin_clzll(x);} // 2^kの位 (x > 0)
i64 bot_bit(i64 x) { return __builtin_ctzll(x);} // 2^kの位 (x > 0)
// i64 next_bit(i64 x, i64 k) { return 0; }
// i64 prev_bit(i64 x, i64 k) { return 0; }
// i64 kth_bit(i64 x, i64 k) { return 0; }
i64 MSB(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // mask
i64 LSB(i64 x) { return (x & -x); } // mask

i64 countl_zero(i64 x) { return __builtin_clzll(x); }
i64 countl_one(i64 x) {
    i64 ret = 0, k = 63 - __builtin_clzll(x);
    while (k != -1 && (x & (1LL << k))) { k--; ret++; }
    return ret;
}
i64 countr_zero(i64 x) { return __builtin_ctzll(x); } // x==0のとき64が返ることに注意
i64 countr_one(i64 x) { i64 ret = 0; while (x & 1) { x >>= 1; ret++; } return ret; }

i64 floor_log2(i64 x) { if (x == 0) return 0; return 63 - __builtin_clzll(x); }
i64 bit_floor(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // MSBと同じ
i64 ceil_log2(i64 x) { if (x == 0) return 0; return 64 - __builtin_clzll(x - 1); }
i64 bit_ceil(i64 x) { if (x == 0) return 0; return 1LL << (64 - __builtin_clzll(x - 1)); }

i64 rotl(i64 x, i64 k) { // 有効bit内でrotate. オーバーフロー注意
    i64 w = bit_width(x); k %= w;
    return ((x << k) | (x >> (w - k))) & ((1LL << w) - 1);
}
// i64 rotl(i64 x, i64 l, i64 m, i64 r) {}
i64 rotr(i64 x, i64 k) {
    i64 w = bit_width(x); k %= w;
    return ((x >> k) | (x << (w - k))) & ((1LL << w) - 1);
}
// i64 rotr(i64 x, i64 l, i64 m, i64 r) {}
i64 bit_reverse(i64 x) { // 有効bit内で左右反転
    i64 r = 0, w = bit_width(x);
    for (i64 i = 0; i < w; i++) r |= ((x >> i) & 1) << (w - i - 1);
    return r;
}
// i64 bit_reverse(i64 x, i64 l, i64 r) { return 0; }

bool is_palindrome(i64 x) { return x == bit_reverse(x); }
bool is_palindrome(i64 x, i64 l, i64 r) { i64 b = sub_bit(x, l, r); return b == bit_reverse(b); }
i64 concat(i64 a, i64 b) { return (a << bit_width(b)) | b; } // オーバーフロー注意
i64 erase(i64 x, i64 l, i64 r) { return x>>r<<l | x&(1LL<<l - 1); } // [l, r) をカット

i64 hamming(i64 a, i64 b) { return __builtin_popcountll(a ^ b); }
i64 hamming(i64 a, i64 b, i64 l, i64 r) { return __builtin_popcountll(sub_bit(a, l, r) ^ sub_bit(b, l, r)); }
i64 compcount(i64 x) { return (__builtin_popcountll(x ^ (x >> 1)) + (x & 1)) / 2; }
i64 compcount2(i64 x) { return compcount(x & (x >> 1)); } // 長さ2以上の連結成分の個数
i64 adjacount(i64 x) { return __builtin_popcountll(x & (x >> 1)); } // 隣接する1のペアの個数

i64 next_combination(i64 x) {
    i64 t = x | (x - 1); return (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctzll(x) + 1));
}


__int128_t POW(__int128_t x, int n) {
    __int128_t ret = 1;
    assert(n >= 0);
    if (x == 1 or n == 0) ret = 1;
    else if (x == -1 && n % 2 == 0) ret = 1; 
    else if (x == -1) ret = -1; 
    else if (n % 2 == 0) {
        assert(x < INFL);
        ret = POW(x * x, n / 2);
    } else {
        assert(x < INFL);
        ret = x * POW(x, n - 1);
    }
    return ret;
}
int per(int x, int y) { // x = qy + r (0 <= r < y) を満たすq
    assert(y != 0);
    if (x >= 0 && y > 0) return x / y;
    if (x >= 0 && y < 0) return x / y - (x % y < 0);
    if (x < 0 && y < 0) return x / y + (x % y < 0);
    return x / y - (x % y < 0); //  (x < 0 && y > 0) 
}
int mod(int x, int y) { // x = qy + r (0 <= r < y) を満たすr
    assert(y != 0);
    if (x >= 0) return x % y;
    __int128_t ret = x % y; // (x < 0)
    ret += (__int128_t)abs(y) * INFL;
    ret %= abs(y);
    return ret;
}
int floor(int x, int y) { // (ld)x / y 以下の最大の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x >= 0 ? x / y : (x + 1) / y - 1;
}
int ceil(int x, int y) { // (ld)x / y 以上の最小の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x > 0 ? (x - 1) / y + 1 : x / y;
}
int round(int x, int y) {
    assert(y != 0);
    return (x * 2 + y) / (y * 2);
}
int round(int x, int y, int k) { // (ld)(x/y)を10^kの位に関して四捨五入
    assert(y != 0); // TODO
    return INF;
}
int round2(int x, int y) { // 五捨五超入 // 未verify
    assert(y != 0);
    if (y < 0) y = -y, x = -x;
    int z = z / y;
    if ((z * 2 + 1) * y <= y * 2) z++;
    return z;
}
// int round(ld x, int k) { // xを10^kの位に関して四捨五入
// }
// int floor(ld x, int k) { // xを10^kの位に関してflooring
// }
// int ceil(ld x, int k) { // xを10^kの位に関してceiling
// }
// int kth(int x, int y, int k) { // x / yの10^kの位の桁
// }
int floor(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return floor(x / y);
    // floor(x) = ceil(x - 1) という話も
}
int ceil(ld x, ld y) { // 誤差対策TODO // ceil(p/q) = -floor(-(p/q))らしい
    assert(!equals(y, 0));
    return ceil(x / y);
    // ceil(x) = floor(x + 1)
}
int perl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす q
    // 未verify. 誤差対策TODO. EPS外してもいいかも。
    assert(!equals(y, 0));
    if (x >= 0 && y > 0) return floor(x / y)+EPS;
    if (x >= 0 && y < 0) return -floor(x / fabs(y));
    if (x < 0 && y < 0) return floor(x / y) + (x - floor(x/y)*y < -EPS);
    return floor(x / y) - (x - floor(x/y)*y < -EPS); //  (x < 0 && y > 0) 
}
ld modl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす r
    // 未verify. 誤差対策TODO. -0.0が返りうる。
    assert(!equals(y, 0));
    if (x >= 0) return x - fabs(y)*fabs(per(x, y));
    return x - fabs(y)*floor(x, fabs(y));
}
int seisuu(ld x) { return (int)x; } // 整数部分. 誤差対策TODO
int modf(ld x) {
	if (x < 0) return ceill(x);
	else return floorl(x);
}
// 正なら+EPS, 負なら-EPSしてから、文字列に直して小数点以下を捨てる?
int seisuu(int x, int y) {
    assert(y != 0);
    return x / y;
}
int seisuu(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return (int)(x / y);
}

template <class T> pair<T, T> max(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first > b.first or a.first == b.first && a.second > b.second) return a;
    return b;
}
template <class T> pair<T, T> min(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first < b.first or a.first == b.first && a.second < b.second) return a;
    return b;
}

template <class T> bool chmax(T &a, const T& b) {
    if (a < b) { a = b; return true; } return false;
}
template <class T> bool chmin(T &a, const T& b) {
    if (a > b) { a = b; return true; } return false;
}
template <class T> T mid(T a, T b, T c) { // 誤差対策TODO
    return a + b + c - max({a, b, c}) - min({a, b, c});
}
template <class T> void Sort(T &a, T &b, bool rev = false) { 
    if (rev == false) {  // TODO テンプレート引数
        if (a > b) swap(a, b);
    } else {
        if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c); if (b > c) swap(b, c);
    } else {
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, T &d, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c);  if (a > d) swap(a, d);
        if (b > c) swap(b, c); if (b > d) swap(b, d); if (c > d) swap(c, d);
    } else {
        if (d > c) swap(d, c); if (d > b) swap(d, b); if (d > a) swap(d, a);
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

class Compress {
public:
    int sz = 0;
    // gp_hash_table<int, int, custom_hash> Z, UZ;
    unordered_map<int, int> Z;    // 元の値 -> 圧縮した値
    unordered_map<int, int> UZ;   // 圧縮した値 -> 元の値

    Compress(const vector<int> &V, int base = 0) {
        this->sz = base;
        set<int> s(V.begin(), V.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }
    
    Compress(const vector<int> &V1, const vector<int> &V2, int base = 0) {
        this->sz = base;
        vector<int> V3 = V2;
        V3.insert(V3.end(), V1.begin(), V1.end());
        set<int> s(V3.begin(), V3.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2, const vector<int> &V3, int base = 0) {
        this->sz = base;
        vector<int> V4 = V1;
        V4.insert(V4.end(), V2.begin(), V2.end());
        V4.insert(V4.end(), V3.begin(), V3.end());
        set<int> s(V4.begin(), V4.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2,
            const vector<int> &V3, const vector<int> &V4, int base = 0) {
        this->sz = base;
        vector<int> V5 = V1;
        V5.insert(V5.end(), V2.begin(), V2.end());
        V5.insert(V5.end(), V3.begin(), V3.end());
        V5.insert(V5.end(), V4.begin(), V4.end());
        set<int> s(V5.begin(), V5.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    vector<int> zip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = Z[ret[i]];
        }
        return ret;
    }

    vector<int> unzip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = UZ[ret[i]];
        }
        return ret;
    }

    int size() { return sz; }

    int encode(int x) { return Z[x]; }
    int decode(int x) {
        if (UZ.find(x) == UZ.end()) return -1; // xが元の配列に存在しないとき
        return UZ[x];
    }
};

class UnionFind {
public:
	UnionFind() = default;
    UnionFind(int N) : par(N), sz(N, 1) {
        iota(par.begin(), par.end(), 0);
    }
	int root(int x) {
		if (par[x] == x) return x;
		return (par[x] = root(par[x]));
	}
	bool unite(int x, int y) {
		int rx = root(x);
		int ry = root(y);
        if (rx == ry) return false;
		if (sz[rx] < sz[ry]) swap(rx, ry);
		sz[rx] += sz[ry];
		par[ry] = rx;
        return true;
	}
	bool issame(int x, int y) { return (root(x) == root(y)); }
	int size(int x) { return sz[root(x)]; }
    vector<vector<int>> groups(int N) {
        vector<vector<int>> G(N);
        for (int x = 0; x < N; x++) {
            G[root(x)].push_back(x);
        }
		G.erase( remove_if(G.begin(), G.end(),
            [&](const vector<int>& V) { return V.empty(); }), G.end());
        return G;
    }
private:
	vector<int> par, sz;
};

template<typename T>
struct BIT {
    int N;             // 要素数
    vector<T> bit[2];  // データの格納先
    BIT(int N_, int x = 0) {
        N = N_ + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        if (x != 0) {
            for (int i = 0; i < N; i++) add(i, x);
        }
    }
    BIT(const vector<int> &A) {
        N = A.size() + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        for (int i = 0; i < (int)A.size(); i++) add(i, A[i]);
    }
    void add_sub(int p, int i, T x) {
        while (i < N) { bit[p][i] += x; i += (i & -i); }
    }
    void add(int l, int r, T x) {
        add_sub(0, l + 1, -x * l); add_sub(0, r + 1, x * r);
        add_sub(1, l + 1, x); add_sub(1, r + 1, -x);
    }
    void add(int i, T x) { add(i, i + 1, x); }
    T sum_sub(int p, int i) {
        T ret = 0;
        while (i > 0) { ret += bit[p][i]; i -= (i & -i); }
        return ret;
    }
    T sum(int i) { return sum_sub(0, i) + sum_sub(1, i) * i; }
    T sum(int l, int r) { return sum(r) - sum(l); }
    T get(int i) { return sum(i, i + 1); }
    void set(int i, T x) { T s = get(i); add(i, -s + x); }
};

#pragma endregion

// #define pb emplace_back
// using ll = long long;
// const int INF = 1 << 30;
// const ll INFL = 1LL << 61;

const int Nmax = 500002, Qmax = 30002, NQmax = 530004, V = 25000005;

int N, Q, A[Nmax], B[NQmax], sz; // 座圧列と座圧後のサイズ？

struct qry {
    int t, l, r, x, k;
} query[Qmax];

int v(int x) {
    return lower_bound(B + 1, B + sz + 1, x) - B;
}

void disc(int N, int Q) { // 座圧
    memcpy(B, A, sizeof A);

    // for (int i = 0; i < Q; i++) {
    //     if (query[i].t != 2) B[++N] = query[i].x;
    // }

    sort(B + 1, B + N + 1);
    sz = unique(B + 1, B + N + 1) - B - 1;
    B[0] = -INF, B[sz + 1] = INF;
}

vector<int> rt(NQmax), xl(NQmax), xr(NQmax);
int vl, vr;
class LOJ {
    class seg {
        int c;

        struct node {
            int l, r, x;
        } a[V];

        void up(int x) {
            a[x].x = a[a[x].l].x + a[a[x].r].x;
        }

    public:

        void add(int p, int x, int &X, int l = 1, int r = sz) {
            a[++c] = a[X], X = c;

            if (l == r) {
                a[X].x += x;
                return;
            }

            int m = l + r >> 1;
            p <= m ? add(p, x, a[X].l, l, m) : add(p, x, a[X].r, m + 1, r);
            up(X);
        }

        int rank(int x, int l = 1, int r = sz) {
            if (l == r) return 1;

            int m = l + r >> 1;

            if (x <= m) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return rank(x, l, m);
            } else {
                int t = 0;

                for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x, xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x, xr[i] = a[xr[i]].r;

                return t + rank(x, m + 1, r);
            }
        }

        int kth_smallest(int x, int l = 1, int r = sz) {
            if (l == r)
                return l;

            int m = l + r >> 1, t = 0;

            for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x;
            for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x;

            if (x <= t) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return kth_smallest(x, l, m);
            } else {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].r;

                return kth_smallest(x - t, m + 1, r);
            }
        }
    } s;

public:

    void add(int p1, int p2, int x) {
        for (int i = p1; i <= N; i += i & -i) s.add(p2, x, rt[i]);
    }

    void _X(int l, int r) {
        vl = vr = 0;

        for (int i = l - 1; i > 0; i &= i - 1) xl[++vl] = rt[i];

        for (int i = r; i > 0; i &= i - 1) xr[++vr] = rt[i];
    }

    int rank(int l, int r, int x) {
        _X(l, r);
        return s.rank(x);
    }

    int count(int l, int r, int x) { // 未verify
        return rank(l, r, x + 1) - rank(l, r, x);
    }

    int count(int l, int r, int a, int b) { // 未verify
        return rank(l, r, b) - rank(l, r, a);
    }

    int kth_smallest(int l, int r, int k) {
        // assert(0 <= k && k < r - l);
        _X(l, r);
        return s.kth_smallest(k);
    }

    int kth_largest(int l, int r, int k) { // 未verify
        return kth_smallest(l, r, r - l - k - 1);
    }

    // int get(int i) {
    //     return kth_smallest(i, i + 1, 0);
    //     return ;
    // }

    int prev_value(int l, int r, int x) {
        int t = rank(l, r, x) - 1;
        return t ? kth_smallest(l, r, t) : 0;
    }

    int next_value(int l, int r, int x) {
        int t = rank(l, r, x + 1);
        return t <= r - l + 1 ? kth_smallest(l, r, t) : sz + 1;
    }
} seg;

signed main() {
    cin >> N;

    // Aの入力は1-indexed
    for (int i = 1; i <= N; i++) cin >> A[i];

    cin >> Q;

    // 区間は1-indexの閉区間
    for (int i = 0; i < Q; i++) {
        cin >> query[i].l >> query[i].r;
    }

    disc(N, Q);

    for (int i = 1; i <= N; i++) seg.add(i, v(A[i]), 1);

    tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> tr;
    int t = 0; // 初めの転倒数
    for (int i = N; i >= 1; i--) {
        tr.insert(A[i]);
        // A[i]未満の個数を逆順に加算していく
        t += tr.order_of_key(A[i]);
    }

    for (int i = 0; i < Q; i++) {
        t -= seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t -= seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        t -= seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        int temp = A[query[i].l];

        seg.add(query[i].l, v(A[query[i].l]), -1);
        A[query[i].l] = A[query[i].r];
        seg.add(query[i].l, v(A[query[i].l]), 1);

        seg.add(query[i].r, v(A[query[i].r]), -1);
        A[query[i].r] = temp;
        seg.add(query[i].r, v(A[query[i].r]), 1);

        t += seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        t += seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t += seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        cout << t << endl;
    }
}
accuracy: 0.7
time_ms: 90
memory_kb: 155616
final_rank: 12

code_snippet: #pragma region Macros

// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,fma,abm,mmx,avx,avx2")

#include <bits/extc++.h>
// #include <atcoder/all>
// using namespace atcoder;
using namespace std;
using namespace __gnu_pbds;

// #include <boost/multiprecision/cpp_dec_float.hpp>
// #include <boost/multiprecision/cpp_int.hpp>
// namespace mp = boost::multiprecision;
// using Bint = mp::cpp_int;
// using Bdouble = mp::number<mp::cpp_dec_float<256>>;
// Bdouble Beps = 0.00000000000000000000000000000001; // 1e-32
// const bool equals(Bdouble a, Bdouble b) { return mp::fabs(a - b) < Beps; }

#define pb emplace_back
#define int ll
#define endl '\n'
// #define unordered_map<int, int> gp_hash_table<int, int, custom_hash> 

#define sqrt __builtin_sqrtl
#define cbrt __builtin_cbrtl
#define hypot __builtin_hypotl

#define next asdnext
#define prev asdprev

using ll = long long;
using ld = long double;
const ld PI = acosl(-1);
const int INF = 1 << 30;
const ll INFL = 1LL << 61;
const int MOD = 998244353;
// const int MOD = 1000000007;

const ld EPS = 1e-10;
const bool equals(ld a, ld b) { return fabs((a) - (b)) < EPS; }

const vector<int> dx = {0, 1, 0, -1, 1, 1, -1, -1}; // → ↓ ← ↑ ↘ ↙ ↖ ↗
const vector<int> dy = {1, 0, -1, 0, 1, -1, -1, 1};

#define EC int
struct Edge {
    int from, to;
    EC cost;
    Edge() : from(-1), to(-1), cost(-1) {}
    Edge(int to, EC cost) : to(to), cost(cost) {}
    Edge(int from, int to, EC cost) : from(from), to(to), cost(cost) {}
    bool operator ==(const Edge& e) {
        return this->from == e.from && this->to == e.to && this->cost == e.cost;
    }
    bool operator !=(const Edge& e) {
        return this->from != e.from or this->to != e.to or this->cost != e.cost;
    }
};

chrono::system_clock::time_point start;
__attribute__((constructor))
void constructor() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(10);
    start = chrono::system_clock::now();
}

random_device seed_gen;
mt19937_64 rng(seed_gen());
uniform_int_distribution<int> dist_x(0, 1e9);
struct RNG {
    unsigned Int(unsigned l, unsigned r) {
        return dist_x(rng) % (r - l + 1) + l;
    }
    ld Double() {
        return ld(dist_x(rng)) / 1e9;
    }
} rnd;

using i64 = ll;
// using i64 = uint64_t;
// bit演算, x==0の場合は例外処理した方がよさそう. 区間は [l, r)
i64 lrmask(i64 l, i64 r) { return (1LL << r) - (1LL << l); }
i64 sub_bit(i64 x, i64 l, i64 r) { i64 b = x & ((1LL << r) - (1LL << l)); return b >> l; } // r溢れ可
i64 bit_width(i64 x) { return 64 - __builtin_clzll(x) + (x == 0); }

i64 popcount(i64 x) { return __builtin_popcountll(x); }
i64 popcount(i64 x, i64 l, i64 r) { return __builtin_popcountll(sub_bit(x, l, r)); }
i64 unpopcount(i64 x) { return bit_width(x) - __builtin_popcountll(x); }
i64 unpopcount(i64 x, i64 l, i64 r) { return r - l - __builtin_popcountll(sub_bit(x, l, r)); }
bool is_pow2(i64 x) { return __builtin_popcountll(x) == 1; } // xが負のときは常にfalse
bool is_pow4(i64 x) { return __builtin_popcount(x) == 1 && __builtin_ctz(x) % 2 == 0; }

i64 top_bit(i64 x) { return 63 - __builtin_clzll(x);} // 2^kの位 (x > 0)
i64 bot_bit(i64 x) { return __builtin_ctzll(x);} // 2^kの位 (x > 0)
// i64 next_bit(i64 x, i64 k) { return 0; }
// i64 prev_bit(i64 x, i64 k) { return 0; }
// i64 kth_bit(i64 x, i64 k) { return 0; }
i64 MSB(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // mask
i64 LSB(i64 x) { return (x & -x); } // mask

i64 countl_zero(i64 x) { return __builtin_clzll(x); }
i64 countl_one(i64 x) {
    i64 ret = 0, k = 63 - __builtin_clzll(x);
    while (k != -1 && (x & (1LL << k))) { k--; ret++; }
    return ret;
}
i64 countr_zero(i64 x) { return __builtin_ctzll(x); } // x==0のとき64が返ることに注意
i64 countr_one(i64 x) { i64 ret = 0; while (x & 1) { x >>= 1; ret++; } return ret; }

i64 floor_log2(i64 x) { if (x == 0) return 0; return 63 - __builtin_clzll(x); }
i64 bit_floor(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // MSBと同じ
i64 ceil_log2(i64 x) { if (x == 0) return 0; return 64 - __builtin_clzll(x - 1); }
i64 bit_ceil(i64 x) { if (x == 0) return 0; return 1LL << (64 - __builtin_clzll(x - 1)); }

i64 rotl(i64 x, i64 k) { // 有効bit内でrotate. オーバーフロー注意
    i64 w = bit_width(x); k %= w;
    return ((x << k) | (x >> (w - k))) & ((1LL << w) - 1);
}
// i64 rotl(i64 x, i64 l, i64 m, i64 r) {}
i64 rotr(i64 x, i64 k) {
    i64 w = bit_width(x); k %= w;
    return ((x >> k) | (x << (w - k))) & ((1LL << w) - 1);
}
// i64 rotr(i64 x, i64 l, i64 m, i64 r) {}
i64 bit_reverse(i64 x) { // 有効bit内で左右反転
    i64 r = 0, w = bit_width(x);
    for (i64 i = 0; i < w; i++) r |= ((x >> i) & 1) << (w - i - 1);
    return r;
}
// i64 bit_reverse(i64 x, i64 l, i64 r) { return 0; }

bool is_palindrome(i64 x) { return x == bit_reverse(x); }
bool is_palindrome(i64 x, i64 l, i64 r) { i64 b = sub_bit(x, l, r); return b == bit_reverse(b); }
i64 concat(i64 a, i64 b) { return (a << bit_width(b)) | b; } // オーバーフロー注意
i64 erase(i64 x, i64 l, i64 r) { return x>>r<<l | x&(1LL<<l - 1); } // [l, r) をカット

i64 hamming(i64 a, i64 b) { return __builtin_popcountll(a ^ b); }
i64 hamming(i64 a, i64 b, i64 l, i64 r) { return __builtin_popcountll(sub_bit(a, l, r) ^ sub_bit(b, l, r)); }
i64 compcount(i64 x) { return (__builtin_popcountll(x ^ (x >> 1)) + (x & 1)) / 2; }
i64 compcount2(i64 x) { return compcount(x & (x >> 1)); } // 長さ2以上の連結成分の個数
i64 adjacount(i64 x) { return __builtin_popcountll(x & (x >> 1)); } // 隣接する1のペアの個数

i64 next_combination(i64 x) {
    i64 t = x | (x - 1); return (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctzll(x) + 1));
}


__int128_t POW(__int128_t x, int n) {
    __int128_t ret = 1;
    assert(n >= 0);
    if (x == 1 or n == 0) ret = 1;
    else if (x == -1 && n % 2 == 0) ret = 1; 
    else if (x == -1) ret = -1; 
    else if (n % 2 == 0) {
        assert(x < INFL);
        ret = POW(x * x, n / 2);
    } else {
        assert(x < INFL);
        ret = x * POW(x, n - 1);
    }
    return ret;
}
int per(int x, int y) { // x = qy + r (0 <= r < y) を満たすq
    assert(y != 0);
    if (x >= 0 && y > 0) return x / y;
    if (x >= 0 && y < 0) return x / y - (x % y < 0);
    if (x < 0 && y < 0) return x / y + (x % y < 0);
    return x / y - (x % y < 0); //  (x < 0 && y > 0) 
}
int mod(int x, int y) { // x = qy + r (0 <= r < y) を満たすr
    assert(y != 0);
    if (x >= 0) return x % y;
    __int128_t ret = x % y; // (x < 0)
    ret += (__int128_t)abs(y) * INFL;
    ret %= abs(y);
    return ret;
}
int floor(int x, int y) { // (ld)x / y 以下の最大の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x >= 0 ? x / y : (x + 1) / y - 1;
}
int ceil(int x, int y) { // (ld)x / y 以上の最小の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x > 0 ? (x - 1) / y + 1 : x / y;
}
int round(int x, int y) {
    assert(y != 0);
    return (x * 2 + y) / (y * 2);
}
int round(int x, int y, int k) { // (ld)(x/y)を10^kの位に関して四捨五入
    assert(y != 0); // TODO
    return INF;
}
int round2(int x, int y) { // 五捨五超入 // 未verify
    assert(y != 0);
    if (y < 0) y = -y, x = -x;
    int z = z / y;
    if ((z * 2 + 1) * y <= y * 2) z++;
    return z;
}
// int round(ld x, int k) { // xを10^kの位に関して四捨五入
// }
// int floor(ld x, int k) { // xを10^kの位に関してflooring
// }
// int ceil(ld x, int k) { // xを10^kの位に関してceiling
// }
// int kth(int x, int y, int k) { // x / yの10^kの位の桁
// }
int floor(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return floor(x / y);
    // floor(x) = ceil(x - 1) という話も
}
int ceil(ld x, ld y) { // 誤差対策TODO // ceil(p/q) = -floor(-(p/q))らしい
    assert(!equals(y, 0));
    return ceil(x / y);
    // ceil(x) = floor(x + 1)
}
int perl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす q
    // 未verify. 誤差対策TODO. EPS外してもいいかも。
    assert(!equals(y, 0));
    if (x >= 0 && y > 0) return floor(x / y)+EPS;
    if (x >= 0 && y < 0) return -floor(x / fabs(y));
    if (x < 0 && y < 0) return floor(x / y) + (x - floor(x/y)*y < -EPS);
    return floor(x / y) - (x - floor(x/y)*y < -EPS); //  (x < 0 && y > 0) 
}
ld modl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす r
    // 未verify. 誤差対策TODO. -0.0が返りうる。
    assert(!equals(y, 0));
    if (x >= 0) return x - fabs(y)*fabs(per(x, y));
    return x - fabs(y)*floor(x, fabs(y));
}
int seisuu(ld x) { return (int)x; } // 整数部分. 誤差対策TODO
int modf(ld x) {
	if (x < 0) return ceill(x);
	else return floorl(x);
}
// 正なら+EPS, 負なら-EPSしてから、文字列に直して小数点以下を捨てる?
int seisuu(int x, int y) {
    assert(y != 0);
    return x / y;
}
int seisuu(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return (int)(x / y);
}

template <class T> pair<T, T> max(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first > b.first or a.first == b.first && a.second > b.second) return a;
    return b;
}
template <class T> pair<T, T> min(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first < b.first or a.first == b.first && a.second < b.second) return a;
    return b;
}

template <class T> bool chmax(T &a, const T& b) {
    if (a < b) { a = b; return true; } return false;
}
template <class T> bool chmin(T &a, const T& b) {
    if (a > b) { a = b; return true; } return false;
}
template <class T> T mid(T a, T b, T c) { // 誤差対策TODO
    return a + b + c - max({a, b, c}) - min({a, b, c});
}
template <class T> void Sort(T &a, T &b, bool rev = false) { 
    if (rev == false) {  // TODO テンプレート引数
        if (a > b) swap(a, b);
    } else {
        if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c); if (b > c) swap(b, c);
    } else {
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, T &d, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c);  if (a > d) swap(a, d);
        if (b > c) swap(b, c); if (b > d) swap(b, d); if (c > d) swap(c, d);
    } else {
        if (d > c) swap(d, c); if (d > b) swap(d, b); if (d > a) swap(d, a);
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

class Compress {
public:
    int sz = 0;
    // gp_hash_table<int, int, custom_hash> Z, UZ;
    unordered_map<int, int> Z;    // 元の値 -> 圧縮した値
    unordered_map<int, int> UZ;   // 圧縮した値 -> 元の値

    Compress(const vector<int> &V, int base = 0) {
        this->sz = base;
        set<int> s(V.begin(), V.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }
    
    Compress(const vector<int> &V1, const vector<int> &V2, int base = 0) {
        this->sz = base;
        vector<int> V3 = V2;
        V3.insert(V3.end(), V1.begin(), V1.end());
        set<int> s(V3.begin(), V3.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2, const vector<int> &V3, int base = 0) {
        this->sz = base;
        vector<int> V4 = V1;
        V4.insert(V4.end(), V2.begin(), V2.end());
        V4.insert(V4.end(), V3.begin(), V3.end());
        set<int> s(V4.begin(), V4.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2,
            const vector<int> &V3, const vector<int> &V4, int base = 0) {
        this->sz = base;
        vector<int> V5 = V1;
        V5.insert(V5.end(), V2.begin(), V2.end());
        V5.insert(V5.end(), V3.begin(), V3.end());
        V5.insert(V5.end(), V4.begin(), V4.end());
        set<int> s(V5.begin(), V5.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    vector<int> zip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = Z[ret[i]];
        }
        return ret;
    }

    vector<int> unzip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = UZ[ret[i]];
        }
        return ret;
    }

    int size() { return sz; }

    int encode(int x) { return Z[x]; }
    int decode(int x) {
        if (UZ.find(x) == UZ.end()) return -1; // xが元の配列に存在しないとき
        return UZ[x];
    }
};

class UnionFind {
public:
	UnionFind() = default;
    UnionFind(int N) : par(N), sz(N, 1) {
        iota(par.begin(), par.end(), 0);
    }
	int root(int x) {
		if (par[x] == x) return x;
		return (par[x] = root(par[x]));
	}
	bool unite(int x, int y) {
		int rx = root(x);
		int ry = root(y);
        if (rx == ry) return false;
		if (sz[rx] < sz[ry]) swap(rx, ry);
		sz[rx] += sz[ry];
		par[ry] = rx;
        return true;
	}
	bool issame(int x, int y) { return (root(x) == root(y)); }
	int size(int x) { return sz[root(x)]; }
    vector<vector<int>> groups(int N) {
        vector<vector<int>> G(N);
        for (int x = 0; x < N; x++) {
            G[root(x)].push_back(x);
        }
		G.erase( remove_if(G.begin(), G.end(),
            [&](const vector<int>& V) { return V.empty(); }), G.end());
        return G;
    }
private:
	vector<int> par, sz;
};

template<typename T>
struct BIT {
    int N;             // 要素数
    vector<T> bit[2];  // データの格納先
    BIT(int N_, int x = 0) {
        N = N_ + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        if (x != 0) {
            for (int i = 0; i < N; i++) add(i, x);
        }
    }
    BIT(const vector<int> &A) {
        N = A.size() + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        for (int i = 0; i < (int)A.size(); i++) add(i, A[i]);
    }
    void add_sub(int p, int i, T x) {
        while (i < N) { bit[p][i] += x; i += (i & -i); }
    }
    void add(int l, int r, T x) {
        add_sub(0, l + 1, -x * l); add_sub(0, r + 1, x * r);
        add_sub(1, l + 1, x); add_sub(1, r + 1, -x);
    }
    void add(int i, T x) { add(i, i + 1, x); }
    T sum_sub(int p, int i) {
        T ret = 0;
        while (i > 0) { ret += bit[p][i]; i -= (i & -i); }
        return ret;
    }
    T sum(int i) { return sum_sub(0, i) + sum_sub(1, i) * i; }
    T sum(int l, int r) { return sum(r) - sum(l); }
    T get(int i) { return sum(i, i + 1); }
    void set(int i, T x) { T s = get(i); add(i, -s + x); }
};

#pragma endregion

// #define pb emplace_back
// using ll = long long;
// const int INF = 1 << 30;
// const ll INFL = 1LL << 61;

const int Nmax = 500001, Qmax = 30001, NQmax = 530002, V = 2500005;

int N, Q, A[Nmax], B[NQmax], sz; // 座圧列と座圧後のサイズ？

struct qry {
    int t, l, r, x, k;
} query[Qmax];

int v(int x) {
    return lower_bound(B + 1, B + sz + 1, x) - B;
}

void disc(int N, int Q) { // 座圧
    memcpy(B, A, sizeof A);

    // for (int i = 0; i < Q; i++) {
    //     if (query[i].t != 2) B[++N] = query[i].x;
    // }

    sort(B + 1, B + N + 1);
    sz = unique(B + 1, B + N + 1) - B - 1;
    B[0] = -INF, B[sz + 1] = INF;
}

vector<int> rt(NQmax), xl(NQmax), xr(NQmax);
int vl, vr;
class LOJ {
    class seg {
        int c;

        struct node {
            int l, r, x;
        } a[V];

        void up(int x) {
            a[x].x = a[a[x].l].x + a[a[x].r].x;
        }

    public:

        void add(int p, int x, int &X, int l = 1, int r = sz) {
            a[++c] = a[X], X = c;

            if (l == r) {
                a[X].x += x;
                return;
            }

            int m = l + r >> 1;
            p <= m ? add(p, x, a[X].l, l, m) : add(p, x, a[X].r, m + 1, r);
            up(X);
        }

        int rank(int x, int l = 1, int r = sz) {
            if (l == r) return 1;

            int m = l + r >> 1;

            if (x <= m) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return rank(x, l, m);
            } else {
                int t = 0;

                for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x, xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x, xr[i] = a[xr[i]].r;

                return t + rank(x, m + 1, r);
            }
        }

        int kth_smallest(int x, int l = 1, int r = sz) {
            if (l == r)
                return l;

            int m = l + r >> 1, t = 0;

            for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x;
            for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x;

            if (x <= t) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return kth_smallest(x, l, m);
            } else {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].r;

                return kth_smallest(x - t, m + 1, r);
            }
        }
    } s;

public:

    void add(int p1, int p2, int x) {
        for (int i = p1; i <= N; i += i & -i) s.add(p2, x, rt[i]);
    }

    void _X(int l, int r) {
        vl = vr = 0;

        for (int i = l - 1; i > 0; i &= i - 1) xl[++vl] = rt[i];

        for (int i = r; i > 0; i &= i - 1) xr[++vr] = rt[i];
    }

    int rank(int l, int r, int x) {
        _X(l, r);
        return s.rank(x);
    }

    int count(int l, int r, int x) { // 未verify
        return rank(l, r, x + 1) - rank(l, r, x);
    }

    int count(int l, int r, int a, int b) { // 未verify
        return rank(l, r, b) - rank(l, r, a);
    }

    int kth_smallest(int l, int r, int k) {
        // assert(0 <= k && k < r - l);
        _X(l, r);
        return s.kth_smallest(k);
    }

    int kth_largest(int l, int r, int k) { // 未verify
        return kth_smallest(l, r, r - l - k - 1);
    }

    // int get(int i) {
    //     return kth_smallest(i, i + 1, 0);
    //     return ;
    // }

    int prev_value(int l, int r, int x) {
        int t = rank(l, r, x) - 1;
        return t ? kth_smallest(l, r, t) : 0;
    }

    int next_value(int l, int r, int x) {
        int t = rank(l, r, x + 1);
        return t <= r - l + 1 ? kth_smallest(l, r, t) : sz + 1;
    }
} seg;

signed main() {
    cin >> N;

    // Aの入力は1-indexed
    for (int i = 1; i <= N; i++) cin >> A[i];

    cin >> Q;

    // 区間は1-indexの閉区間
    for (int i = 0; i < Q; i++) {
        cin >> query[i].l >> query[i].r;
    }

    disc(N, Q);

    for (int i = 1; i <= N; i++) seg.add(i, v(A[i]), 1);

    tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> tr;
    int t = 0; // 初めの転倒数
    for (int i = N; i >= 1; i--) {
        tr.insert(A[i]);
        // A[i]未満の個数を逆順に加算していく
        t += tr.order_of_key(A[i]);
    }

    for (int i = 0; i < Q; i++) {
        t -= seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t -= seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        t -= seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        int temp = A[query[i].l];

        seg.add(query[i].l, v(A[query[i].l]), -1);
        A[query[i].l] = A[query[i].r];
        seg.add(query[i].l, v(A[query[i].l]), 1);

        seg.add(query[i].r, v(A[query[i].r]), -1);
        A[query[i].r] = temp;
        seg.add(query[i].r, v(A[query[i].r]), 1);

        t += seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        t += seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t += seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        cout << t << endl;
    }
}
accuracy: 0.65
time_ms: 10
memory_kb: 52484
final_rank: 16

code_snippet: #pragma region Macros

// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,fma,abm,mmx,avx,avx2")

#include <bits/extc++.h>
// #include <atcoder/all>
// using namespace atcoder;
using namespace std;
using namespace __gnu_pbds;

// #include <boost/multiprecision/cpp_dec_float.hpp>
// #include <boost/multiprecision/cpp_int.hpp>
// namespace mp = boost::multiprecision;
// using Bint = mp::cpp_int;
// using Bdouble = mp::number<mp::cpp_dec_float<256>>;
// Bdouble Beps = 0.00000000000000000000000000000001; // 1e-32
// const bool equals(Bdouble a, Bdouble b) { return mp::fabs(a - b) < Beps; }

#define pb emplace_back
#define int ll
#define endl '\n'
// #define unordered_map<int, int> gp_hash_table<int, int, custom_hash> 

#define sqrt __builtin_sqrtl
#define cbrt __builtin_cbrtl
#define hypot __builtin_hypotl

#define next asdnext
#define prev asdprev

using ll = long long;
using ld = long double;
const ld PI = acosl(-1);
const int INF = 1 << 30;
const ll INFL = 1LL << 61;
const int MOD = 998244353;
// const int MOD = 1000000007;

const ld EPS = 1e-10;
const bool equals(ld a, ld b) { return fabs((a) - (b)) < EPS; }

const vector<int> dx = {0, 1, 0, -1, 1, 1, -1, -1}; // → ↓ ← ↑ ↘ ↙ ↖ ↗
const vector<int> dy = {1, 0, -1, 0, 1, -1, -1, 1};

#define EC int
struct Edge {
    int from, to;
    EC cost;
    Edge() : from(-1), to(-1), cost(-1) {}
    Edge(int to, EC cost) : to(to), cost(cost) {}
    Edge(int from, int to, EC cost) : from(from), to(to), cost(cost) {}
    bool operator ==(const Edge& e) {
        return this->from == e.from && this->to == e.to && this->cost == e.cost;
    }
    bool operator !=(const Edge& e) {
        return this->from != e.from or this->to != e.to or this->cost != e.cost;
    }
};

chrono::system_clock::time_point start;
__attribute__((constructor))
void constructor() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(10);
    start = chrono::system_clock::now();
}

random_device seed_gen;
mt19937_64 rng(seed_gen());
uniform_int_distribution<int> dist_x(0, 1e9);
struct RNG {
    unsigned Int(unsigned l, unsigned r) {
        return dist_x(rng) % (r - l + 1) + l;
    }
    ld Double() {
        return ld(dist_x(rng)) / 1e9;
    }
} rnd;

using i64 = ll;
// using i64 = uint64_t;
// bit演算, x==0の場合は例外処理した方がよさそう. 区間は [l, r)
i64 lrmask(i64 l, i64 r) { return (1LL << r) - (1LL << l); }
i64 sub_bit(i64 x, i64 l, i64 r) { i64 b = x & ((1LL << r) - (1LL << l)); return b >> l; } // r溢れ可
i64 bit_width(i64 x) { return 64 - __builtin_clzll(x) + (x == 0); }

i64 popcount(i64 x) { return __builtin_popcountll(x); }
i64 popcount(i64 x, i64 l, i64 r) { return __builtin_popcountll(sub_bit(x, l, r)); }
i64 unpopcount(i64 x) { return bit_width(x) - __builtin_popcountll(x); }
i64 unpopcount(i64 x, i64 l, i64 r) { return r - l - __builtin_popcountll(sub_bit(x, l, r)); }
bool is_pow2(i64 x) { return __builtin_popcountll(x) == 1; } // xが負のときは常にfalse
bool is_pow4(i64 x) { return __builtin_popcount(x) == 1 && __builtin_ctz(x) % 2 == 0; }

i64 top_bit(i64 x) { return 63 - __builtin_clzll(x);} // 2^kの位 (x > 0)
i64 bot_bit(i64 x) { return __builtin_ctzll(x);} // 2^kの位 (x > 0)
// i64 next_bit(i64 x, i64 k) { return 0; }
// i64 prev_bit(i64 x, i64 k) { return 0; }
// i64 kth_bit(i64 x, i64 k) { return 0; }
i64 MSB(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // mask
i64 LSB(i64 x) { return (x & -x); } // mask

i64 countl_zero(i64 x) { return __builtin_clzll(x); }
i64 countl_one(i64 x) {
    i64 ret = 0, k = 63 - __builtin_clzll(x);
    while (k != -1 && (x & (1LL << k))) { k--; ret++; }
    return ret;
}
i64 countr_zero(i64 x) { return __builtin_ctzll(x); } // x==0のとき64が返ることに注意
i64 countr_one(i64 x) { i64 ret = 0; while (x & 1) { x >>= 1; ret++; } return ret; }

i64 floor_log2(i64 x) { if (x == 0) return 0; return 63 - __builtin_clzll(x); }
i64 bit_floor(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // MSBと同じ
i64 ceil_log2(i64 x) { if (x == 0) return 0; return 64 - __builtin_clzll(x - 1); }
i64 bit_ceil(i64 x) { if (x == 0) return 0; return 1LL << (64 - __builtin_clzll(x - 1)); }

i64 rotl(i64 x, i64 k) { // 有効bit内でrotate. オーバーフロー注意
    i64 w = bit_width(x); k %= w;
    return ((x << k) | (x >> (w - k))) & ((1LL << w) - 1);
}
// i64 rotl(i64 x, i64 l, i64 m, i64 r) {}
i64 rotr(i64 x, i64 k) {
    i64 w = bit_width(x); k %= w;
    return ((x >> k) | (x << (w - k))) & ((1LL << w) - 1);
}
// i64 rotr(i64 x, i64 l, i64 m, i64 r) {}
i64 bit_reverse(i64 x) { // 有効bit内で左右反転
    i64 r = 0, w = bit_width(x);
    for (i64 i = 0; i < w; i++) r |= ((x >> i) & 1) << (w - i - 1);
    return r;
}
// i64 bit_reverse(i64 x, i64 l, i64 r) { return 0; }

bool is_palindrome(i64 x) { return x == bit_reverse(x); }
bool is_palindrome(i64 x, i64 l, i64 r) { i64 b = sub_bit(x, l, r); return b == bit_reverse(b); }
i64 concat(i64 a, i64 b) { return (a << bit_width(b)) | b; } // オーバーフロー注意
i64 erase(i64 x, i64 l, i64 r) { return x>>r<<l | x&(1LL<<l - 1); } // [l, r) をカット

i64 hamming(i64 a, i64 b) { return __builtin_popcountll(a ^ b); }
i64 hamming(i64 a, i64 b, i64 l, i64 r) { return __builtin_popcountll(sub_bit(a, l, r) ^ sub_bit(b, l, r)); }
i64 compcount(i64 x) { return (__builtin_popcountll(x ^ (x >> 1)) + (x & 1)) / 2; }
i64 compcount2(i64 x) { return compcount(x & (x >> 1)); } // 長さ2以上の連結成分の個数
i64 adjacount(i64 x) { return __builtin_popcountll(x & (x >> 1)); } // 隣接する1のペアの個数

i64 next_combination(i64 x) {
    i64 t = x | (x - 1); return (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctzll(x) + 1));
}


__int128_t POW(__int128_t x, int n) {
    __int128_t ret = 1;
    assert(n >= 0);
    if (x == 1 or n == 0) ret = 1;
    else if (x == -1 && n % 2 == 0) ret = 1; 
    else if (x == -1) ret = -1; 
    else if (n % 2 == 0) {
        assert(x < INFL);
        ret = POW(x * x, n / 2);
    } else {
        assert(x < INFL);
        ret = x * POW(x, n - 1);
    }
    return ret;
}
int per(int x, int y) { // x = qy + r (0 <= r < y) を満たすq
    assert(y != 0);
    if (x >= 0 && y > 0) return x / y;
    if (x >= 0 && y < 0) return x / y - (x % y < 0);
    if (x < 0 && y < 0) return x / y + (x % y < 0);
    return x / y - (x % y < 0); //  (x < 0 && y > 0) 
}
int mod(int x, int y) { // x = qy + r (0 <= r < y) を満たすr
    assert(y != 0);
    if (x >= 0) return x % y;
    __int128_t ret = x % y; // (x < 0)
    ret += (__int128_t)abs(y) * INFL;
    ret %= abs(y);
    return ret;
}
int floor(int x, int y) { // (ld)x / y 以下の最大の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x >= 0 ? x / y : (x + 1) / y - 1;
}
int ceil(int x, int y) { // (ld)x / y 以上の最小の整数
    assert(y != 0);
    if (y < 0) x = -x, y = -y;
    return x > 0 ? (x - 1) / y + 1 : x / y;
}
int round(int x, int y) {
    assert(y != 0);
    return (x * 2 + y) / (y * 2);
}
int round(int x, int y, int k) { // (ld)(x/y)を10^kの位に関して四捨五入
    assert(y != 0); // TODO
    return INF;
}
int round2(int x, int y) { // 五捨五超入 // 未verify
    assert(y != 0);
    if (y < 0) y = -y, x = -x;
    int z = z / y;
    if ((z * 2 + 1) * y <= y * 2) z++;
    return z;
}
// int round(ld x, int k) { // xを10^kの位に関して四捨五入
// }
// int floor(ld x, int k) { // xを10^kの位に関してflooring
// }
// int ceil(ld x, int k) { // xを10^kの位に関してceiling
// }
// int kth(int x, int y, int k) { // x / yの10^kの位の桁
// }
int floor(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return floor(x / y);
    // floor(x) = ceil(x - 1) という話も
}
int ceil(ld x, ld y) { // 誤差対策TODO // ceil(p/q) = -floor(-(p/q))らしい
    assert(!equals(y, 0));
    return ceil(x / y);
    // ceil(x) = floor(x + 1)
}
int perl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす q
    // 未verify. 誤差対策TODO. EPS外してもいいかも。
    assert(!equals(y, 0));
    if (x >= 0 && y > 0) return floor(x / y)+EPS;
    if (x >= 0 && y < 0) return -floor(x / fabs(y));
    if (x < 0 && y < 0) return floor(x / y) + (x - floor(x/y)*y < -EPS);
    return floor(x / y) - (x - floor(x/y)*y < -EPS); //  (x < 0 && y > 0) 
}
ld modl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす r
    // 未verify. 誤差対策TODO. -0.0が返りうる。
    assert(!equals(y, 0));
    if (x >= 0) return x - fabs(y)*fabs(per(x, y));
    return x - fabs(y)*floor(x, fabs(y));
}
int seisuu(ld x) { return (int)x; } // 整数部分. 誤差対策TODO
int modf(ld x) {
	if (x < 0) return ceill(x);
	else return floorl(x);
}
// 正なら+EPS, 負なら-EPSしてから、文字列に直して小数点以下を捨てる?
int seisuu(int x, int y) {
    assert(y != 0);
    return x / y;
}
int seisuu(ld x, ld y) { // 誤差対策TODO
    assert(!equals(y, 0));
    return (int)(x / y);
}

template <class T> pair<T, T> max(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first > b.first or a.first == b.first && a.second > b.second) return a;
    return b;
}
template <class T> pair<T, T> min(const pair<T, T> &a, const pair<T, T> &b) {
    if (a.first < b.first or a.first == b.first && a.second < b.second) return a;
    return b;
}

template <class T> bool chmax(T &a, const T& b) {
    if (a < b) { a = b; return true; } return false;
}
template <class T> bool chmin(T &a, const T& b) {
    if (a > b) { a = b; return true; } return false;
}
template <class T> T mid(T a, T b, T c) { // 誤差対策TODO
    return a + b + c - max({a, b, c}) - min({a, b, c});
}
template <class T> void Sort(T &a, T &b, bool rev = false) { 
    if (rev == false) {  // TODO テンプレート引数
        if (a > b) swap(a, b);
    } else {
        if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c); if (b > c) swap(b, c);
    } else {
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}
template <class T> void Sort(T &a, T &b, T &c, T &d, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c);  if (a > d) swap(a, d);
        if (b > c) swap(b, c); if (b > d) swap(b, d); if (c > d) swap(c, d);
    } else {
        if (d > c) swap(d, c); if (d > b) swap(d, b); if (d > a) swap(d, a);
        if (c > b) swap(c, b); if (c > a) swap(c, a); if (b > a) swap(b, a);
    }
}

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

class Compress {
public:
    int sz = 0;
    // gp_hash_table<int, int, custom_hash> Z, UZ;
    unordered_map<int, int> Z;    // 元の値 -> 圧縮した値
    unordered_map<int, int> UZ;   // 圧縮した値 -> 元の値

    Compress(const vector<int> &V, int base = 0) {
        this->sz = base;
        set<int> s(V.begin(), V.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }
    
    Compress(const vector<int> &V1, const vector<int> &V2, int base = 0) {
        this->sz = base;
        vector<int> V3 = V2;
        V3.insert(V3.end(), V1.begin(), V1.end());
        set<int> s(V3.begin(), V3.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2, const vector<int> &V3, int base = 0) {
        this->sz = base;
        vector<int> V4 = V1;
        V4.insert(V4.end(), V2.begin(), V2.end());
        V4.insert(V4.end(), V3.begin(), V3.end());
        set<int> s(V4.begin(), V4.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    Compress(const vector<int> &V1, const vector<int> &V2,
            const vector<int> &V3, const vector<int> &V4, int base = 0) {
        this->sz = base;
        vector<int> V5 = V1;
        V5.insert(V5.end(), V2.begin(), V2.end());
        V5.insert(V5.end(), V3.begin(), V3.end());
        V5.insert(V5.end(), V4.begin(), V4.end());
        set<int> s(V5.begin(), V5.end());

        for (int x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }

    vector<int> zip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = Z[ret[i]];
        }
        return ret;
    }

    vector<int> unzip(const vector<int> &V) {
        vector<int> ret = V;
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = UZ[ret[i]];
        }
        return ret;
    }

    int size() { return sz; }

    int encode(int x) { return Z[x]; }
    int decode(int x) {
        if (UZ.find(x) == UZ.end()) return -1; // xが元の配列に存在しないとき
        return UZ[x];
    }
};

class UnionFind {
public:
	UnionFind() = default;
    UnionFind(int N) : par(N), sz(N, 1) {
        iota(par.begin(), par.end(), 0);
    }
	int root(int x) {
		if (par[x] == x) return x;
		return (par[x] = root(par[x]));
	}
	bool unite(int x, int y) {
		int rx = root(x);
		int ry = root(y);
        if (rx == ry) return false;
		if (sz[rx] < sz[ry]) swap(rx, ry);
		sz[rx] += sz[ry];
		par[ry] = rx;
        return true;
	}
	bool issame(int x, int y) { return (root(x) == root(y)); }
	int size(int x) { return sz[root(x)]; }
    vector<vector<int>> groups(int N) {
        vector<vector<int>> G(N);
        for (int x = 0; x < N; x++) {
            G[root(x)].push_back(x);
        }
		G.erase( remove_if(G.begin(), G.end(),
            [&](const vector<int>& V) { return V.empty(); }), G.end());
        return G;
    }
private:
	vector<int> par, sz;
};

template<typename T>
struct BIT {
    int N;             // 要素数
    vector<T> bit[2];  // データの格納先
    BIT(int N_, int x = 0) {
        N = N_ + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        if (x != 0) {
            for (int i = 0; i < N; i++) add(i, x);
        }
    }
    BIT(const vector<int> &A) {
        N = A.size() + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        for (int i = 0; i < (int)A.size(); i++) add(i, A[i]);
    }
    void add_sub(int p, int i, T x) {
        while (i < N) { bit[p][i] += x; i += (i & -i); }
    }
    void add(int l, int r, T x) {
        add_sub(0, l + 1, -x * l); add_sub(0, r + 1, x * r);
        add_sub(1, l + 1, x); add_sub(1, r + 1, -x);
    }
    void add(int i, T x) { add(i, i + 1, x); }
    T sum_sub(int p, int i) {
        T ret = 0;
        while (i > 0) { ret += bit[p][i]; i -= (i & -i); }
        return ret;
    }
    T sum(int i) { return sum_sub(0, i) + sum_sub(1, i) * i; }
    T sum(int l, int r) { return sum(r) - sum(l); }
    T get(int i) { return sum(i, i + 1); }
    void set(int i, T x) { T s = get(i); add(i, -s + x); }
};

#pragma endregion

// #define pb emplace_back
// using ll = long long;
// const int INF = 1 << 30;
// const ll INFL = 1LL << 61;

const int Nmax = 500001, Qmax = 30001, NQmax = 530002, V = 25000005;

int N, Q, A[Nmax], B[NQmax], sz; // 座圧列と座圧後のサイズ？

struct qry {
    int t, l, r, x, k;
} query[Qmax];

int v(int x) {
    return lower_bound(B + 1, B + sz + 1, x) - B;
}

void disc(int N, int Q) { // 座圧
    memcpy(B, A, sizeof A);

    // for (int i = 0; i < Q; i++) {
    //     if (query[i].t != 2) B[++N] = query[i].x;
    // }

    sort(B + 1, B + N + 1);
    sz = unique(B + 1, B + N + 1) - B - 1;
    B[0] = -INF, B[sz + 1] = INF;
}

vector<int> rt(NQmax), xl(NQmax), xr(NQmax);
int vl, vr;
class LOJ {
    class seg {
        int c;

        struct node {
            int l, r, x;
        } a[V];

        void up(int x) {
            a[x].x = a[a[x].l].x + a[a[x].r].x;
        }

    public:

        void add(int p, int x, int &X, int l = 1, int r = sz) {
            a[++c] = a[X], X = c;

            if (l == r) {
                a[X].x += x;
                return;
            }

            int m = l + r >> 1;
            p <= m ? add(p, x, a[X].l, l, m) : add(p, x, a[X].r, m + 1, r);
            up(X);
        }

        int rank(int x, int l = 1, int r = sz) {
            if (l == r) return 1;

            int m = l + r >> 1;

            if (x <= m) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return rank(x, l, m);
            } else {
                int t = 0;

                for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x, xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x, xr[i] = a[xr[i]].r;

                return t + rank(x, m + 1, r);
            }
        }

        int kth_smallest(int x, int l = 1, int r = sz) {
            if (l == r)
                return l;

            int m = l + r >> 1, t = 0;

            for (int i = 1; i <= vl; i++) t -= a[a[xl[i]].l].x;
            for (int i = 1; i <= vr; i++) t += a[a[xr[i]].l].x;

            if (x <= t) {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].l;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].l;

                return kth_smallest(x, l, m);
            } else {
                for (int i = 1; i <= vl; i++) xl[i] = a[xl[i]].r;
                for (int i = 1; i <= vr; i++) xr[i] = a[xr[i]].r;

                return kth_smallest(x - t, m + 1, r);
            }
        }
    } s;

public:

    void add(int p1, int p2, int x) {
        for (int i = p1; i <= N; i += i & -i) s.add(p2, x, rt[i]);
    }

    void _X(int l, int r) {
        vl = vr = 0;

        for (int i = l - 1; i > 0; i &= i - 1) xl[++vl] = rt[i];

        for (int i = r; i > 0; i &= i - 1) xr[++vr] = rt[i];
    }

    int rank(int l, int r, int x) {
        _X(l, r);
        return s.rank(x);
    }

    int count(int l, int r, int x) { // 未verify
        return rank(l, r, x + 1) - rank(l, r, x);
    }

    int count(int l, int r, int a, int b) { // 未verify
        return rank(l, r, b) - rank(l, r, a);
    }

    int kth_smallest(int l, int r, int k) {
        // assert(0 <= k && k < r - l);
        _X(l, r);
        return s.kth_smallest(k);
    }

    int kth_largest(int l, int r, int k) { // 未verify
        return kth_smallest(l, r, r - l - k - 1);
    }

    // int get(int i) {
    //     return kth_smallest(i, i + 1, 0);
    //     return ;
    // }

    int prev_value(int l, int r, int x) {
        int t = rank(l, r, x) - 1;
        return t ? kth_smallest(l, r, t) : 0;
    }

    int next_value(int l, int r, int x) {
        int t = rank(l, r, x + 1);
        return t <= r - l + 1 ? kth_smallest(l, r, t) : sz + 1;
    }
} seg;

signed main() {
    cin >> N;

    // Aの入力は1-indexed
    for (int i = 1; i <= N; i++) cin >> A[i];

    cin >> Q;

    // 区間は1-indexの閉区間
    for (int i = 0; i < Q; i++) {
        cin >> query[i].l >> query[i].r;
    }

    disc(N, Q);

    for (int i = 1; i <= N; i++) seg.add(i, v(A[i]), 1);

    tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> tr;
    int t = 0; // 初めの転倒数
    for (int i = N; i >= 1; i--) {
        tr.insert(A[i]);
        // A[i]未満の個数を逆順に加算していく
        t += tr.order_of_key(A[i]);
    }

    for (int i = 0; i < Q; i++) {
        t -= seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t -= seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        t -= seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        int temp = A[query[i].l];

        seg.add(query[i].l, v(A[query[i].l]), -1);
        A[query[i].l] = A[query[i].r];
        seg.add(query[i].l, v(A[query[i].l]), 1);

        seg.add(query[i].r, v(A[query[i].r]), -1);
        A[query[i].r] = temp;
        seg.add(query[i].r, v(A[query[i].r]), 1);

        t += seg.count(query[i].l + 1, query[i].r, A[query[i].r] + 1, NQmax);

        t += seg.count(query[i].l + 1, N, 0, A[query[i].l]);
        t += seg.count(query[i].r + 1, N, 0, A[query[i].r]);

        cout << t << endl;
    }
}
accuracy: 0.7
time_ms: 100
memory_kb: 155492
final_rank: 13

code_snippet: #include <bits/stdc++.h>

struct Compressor {
    std::vector<int> data;
    Compressor() {}
    void add(int value) {
        data.push_back(value);
    }
    void build() {
        std::sort(data.begin(), data.end());
        data.erase(std::unique(data.begin(), data.end()), data.end());
    }
    int size() {
        return data.size();
    }
    int compress(int value) {
        return std::lower_bound(data.begin(), data.end(), value) - data.begin();
    }
    int operator[](int value) {
        return std::lower_bound(data.begin(), data.end(), value) - data.begin();
    }
};

struct BIT {
    int n;
    std::vector<int> data;
    BIT() {}
    BIT(int n): n(n), data(n + 1) {}
    void insert(int key) {
        for (key++; key <= n; key += key & -key) {
            data[key]++;
        }
    }
    void erase(int key) {
        for (key++; key <= n; key += key & -key) {
            data[key]--;
        }
    }
    int sum(int upper) {
        int res = 0;
        for (; upper > 0; upper -= upper & -upper) {
            res += data[upper];
        }
        return res;
    }
    int sum(int lower, int upper) {
        return sum(upper) - sum(lower);
    }
};

int main() {
    std::cin.tie(0)->sync_with_stdio(0);
    int n;
    std::cin >> n;
    std::vector<int> a(n);
    for (int i = 0; i < n; i++) std::cin >> a[i];
    {
        auto b = a;
        std::sort(b.begin(), b.end());
        for (int i = 0; i < n; i++) {
            a[i] = std::distance(b.begin(), std::lower_bound(b.begin(), b.end(), a[i]));
        }
    }

    const int B = 3500;
    const int bucket_num = (n + B - 1) / B;
    std::vector<Compressor> compressor(bucket_num);
    for (int i = 0; i < n; i++) {
        compressor[i / B].add(a[i]);
    }

    int m;
    std::cin >> m;
    std::vector<std::pair<int, int>> query;
    query.reserve(m);
    {
        auto b = a;
        for (int i = 0; i < m; i++) {
            int u, v;
            std::cin >> u >> v;
            u--;
            v--;
            query.emplace_back(u, v);
            std::swap(b[u], b[v]);
            compressor[u / B].add(b[u]);
            compressor[v / B].add(b[v]);
        }
    }
    for (int i = 0; i < bucket_num; i++) {
        compressor[i].build();
    }

    std::vector<BIT> bucket(bucket_num);
    for (int i = 0; i < bucket_num; i++) {
        bucket[i] = BIT(compressor[i].size());
    }
    for (int i = 0; i < n; i++) {
        bucket[i / B].insert(compressor[i / B][a[i]]);
    }
    long long ans = 0;
    {
        BIT bit(n);
        for (int i = 0; i < n; i++) {
            ans += bit.sum(a[i], n);
            bit.insert(a[i]);
        }
    }

    auto contribute = [&](int u) {
        const int offset = (u / B) * B;
        long long res = 0;
        for (int i = 0; i < u / B; i++) {
            res += bucket[i].sum(compressor[i][a[u]], compressor[i][n]);
        }
        for (int i = offset, right = std::min(offset + B, n); i < right; i++) {
            if (i < u && a[i] > a[u])
                res++;
            else if (i > u && a[i] < a[u])
                res++;
        }
        for (int i = (offset / B) + 1; i < bucket_num; i++) {
            res += bucket[i].sum(compressor[i][a[u]]);
        }
        return res;
    };

    for (int i = 0; i < m; i++) {
        auto [u, v] = query[i];

        ans -= contribute(u) + contribute(v);
        if (a[u] > a[v]) ans++;
        bucket[u / B].erase(compressor[u / B][a[u]]);
        bucket[v / B].erase(compressor[v / B][a[v]]);
        bucket[u / B].insert(compressor[u / B][a[v]]);
        bucket[v / B].insert(compressor[v / B][a[u]]);
        std::swap(a[u], a[v]);
        ans += contribute(u) + contribute(v);
        if (a[u] > a[v]) ans--;
        std::cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 2280
memory_kb: 12024
final_rank: 7

code_snippet: #include <bits/stdc++.h>

int n;

struct Node;
using NodePtr = Node*;
struct Node {
    NodePtr left = nullptr;
    NodePtr right = nullptr;
    int value = 0;
};

struct NodeManager {
    static constexpr int N = 1000000;
    int pos = 0;
    std::array<Node, N> nodes;
    NodeManager() {}
    bool limit() {
        return N - pos < 20000;
    }
    void init() {
        for (int i = 0; i < pos; i++) {
            nodes[i].left = nullptr;
            nodes[i].right = nullptr;
            nodes[i].value = 0;
        }
        pos = 0;
    }
    NodePtr make_node() {
        return &nodes[pos++];
    }
    NodePtr make_node(NodePtr node) {
        nodes[pos].left = node->left;
        nodes[pos].right = node->right;
        nodes[pos].value = node->value;
        return &nodes[pos++];
    }
};
NodeManager NM;

NodePtr insert(NodePtr root, int key) {
    NodePtr result = NM.make_node(root);
    NodePtr node = result;
    int left = 0;
    int right = n;
    while (right - left > 1) {
        assert(node);
        node->value++;
        int mid = (left + right) / 2;
        if (left <= key && key < mid) {
            if (node->left) {
                node->left = NM.make_node(node->left);
            } else {
                node->left = NM.make_node();
            }
            node = node->left;
            right = mid;
        } else {
            if (node->right) {
                node->right = NM.make_node(node->right);
            } else {
                node->right = NM.make_node();
            }
            node = node->right;
            left = mid;
        }
    }
    assert(key == left);
    // assert(node->value == 0);
    node->value++;
    return result;
}

NodePtr erase(NodePtr root, int key) {
    NodePtr result = NM.make_node(root);
    NodePtr node = result;
    int left = 0;
    int right = n;
    while (right - left > 1) {
        assert(node);
        // assert(node->value > 0);
        node->value--;
        int mid = (left + right) / 2;
        if (left <= key && key < mid) {
            if (node->left) {
                node->left = NM.make_node(node->left);
            } else {
                node->left = NM.make_node();
            }
            node = node->left;
            right = mid;
        } else {
            if (node->right) {
                node->right = NM.make_node(node->right);
            } else {
                node->right = NM.make_node();
            }
            node = node->right;
            left = mid;
        }
    }
    assert(key == left);
    // assert(node->value == 1);
    node->value--;
    return result;
}

int prod(NodePtr root, int left, int right) {
    auto dfs = [&](auto self, NodePtr node, int l, int r) -> int {
        if (!node) return 0;
        if (left <= l && r <= right) {
            return node->value;
        } else if (r <= left || right <= l) {
            return 0;
        } else {
            int m = (l + r) / 2;
            return self(self, node->left, l, m) + self(self, node->right, m, r);
        }
    };
    return dfs(dfs, root, 0, n);
}

int main() {
    std::cin >> n;
    std::vector<int> a(n);
    for (int i = 0; i < n; i++) std::cin >> a[i];
    {
        auto b = a;
        std::sort(b.begin(), b.end());
        for (int i = 0; i < n; i++) {
            a[i] = std::distance(b.begin(), std::lower_bound(b.begin(), b.end(), a[i]));
        }
    }


    int q;
    std::cin >> q;
    std::vector<std::tuple<int, int, int, int>> query;
    query.reserve(q);
    {
        auto b = a;
        for (int i = 0; i < q; i++) {
            int u, v;
            std::cin >> u >> v;
            u--; v--;
            query.emplace_back(u, v, b[u], b[v]);
            std::swap(b[u], b[v]);
        }
    }

    std::vector<NodePtr> roots(n);
    auto init = [&](int t) {
        NM.init();
        roots[0] = NM.make_node();
        for (int i = 0; i + 1 < n; i++) {
            roots[i + 1] = insert(roots[i], a[i]);
        }
        long long inv = 0;
        for (int i = 0; i < n; i++) {
            inv += prod(roots[i], a[i], n);
        }
        return inv;
    };

    const int B = 500;
    // 次に処理すべきクエリ番号
    std::vector<int> last_update(n);
    long long ans = 0;
    for (int t = 0; t < q; t++) {
        if (t % B == 0 || NM.limit()) {
            ans = init(t);
            last_update.assign(n, t);
        }
        auto [u, v, lv, rv] = query[t];

        // 1. 遅延していたswap処理を行う
        for (auto i: {u, v}) {
            for (; last_update[i] < t; last_update[i]++) {
                int cur = last_update[i];
                auto [p, q, lhs, rhs] = query[cur];
                if (p < i) {
                    roots[i] = insert(erase(roots[i], lhs), rhs);
                }
                if (q < i) {
                    roots[i] = insert(erase(roots[i], rhs), lhs);
                }
            }
        }

        auto contribute = [&](int pos) {
            int left_large = prod(roots[pos], a[pos], n);
            int left_small = (pos - left_large);
            int right_small = a[pos] - left_small;
            return left_large + right_small;
        };

        // 2. 寄与を削除
        ans -= contribute(u) + contribute(v);
        if (a[u] > a[v]) ans++;

        // 3. swap, swapによる寄与を追加
        std::swap(a[u], a[v]);
        ans += contribute(u);
        roots[v] = insert(erase(roots[v], lv), rv);
        ans += contribute(v);
        if (a[u] > a[v]) ans--;

        last_update[u] = t + 1;
        last_update[v] = t + 1;
        assert(a[u] == rv);
        assert(a[v] == lv);

        std::cout << ans << '\n';
    }
}
accuracy: 0.7
time_ms: 430
memory_kb: 26924
final_rank: 11

code_snippet: #include <bits/stdc++.h>

int n;

struct Node;
using NodePtr = Node*;
struct Node {
    NodePtr left = nullptr;
    NodePtr right = nullptr;
    int value = 0;
};

struct NodeManager {
    static constexpr int N = 200000;
    int pos = 0;
    std::array<Node, N> nodes;
    NodeManager() {}
    bool limit() {
        return N - pos < 10000;
    }
    void init() {
        for (int i = 0; i < pos; i++) {
            nodes[i].left = nullptr;
            nodes[i].right = nullptr;
            nodes[i].value = 0;
        }
        pos = 0;
    }
    NodePtr make_node() {
        return &nodes[pos++];
    }
    NodePtr make_node(NodePtr node) {
        nodes[pos].left = node->left;
        nodes[pos].right = node->right;
        nodes[pos].value = node->value;
        return &nodes[pos++];
    }
};
NodeManager NM;

NodePtr insert(NodePtr root, int key) {
    NodePtr result = NM.make_node(root);
    NodePtr node = result;
    int left = 0;
    int right = n;
    while (right - left > 1) {
        assert(node);
        node->value++;
        int mid = (left + right) / 2;
        if (left <= key && key < mid) {
            if (node->left) {
                node->left = NM.make_node(node->left);
            } else {
                node->left = NM.make_node();
            }
            node = node->left;
            right = mid;
        } else {
            if (node->right) {
                node->right = NM.make_node(node->right);
            } else {
                node->right = NM.make_node();
            }
            node = node->right;
            left = mid;
        }
    }
    assert(key == left);
    // assert(node->value == 0);
    node->value++;
    return result;
}

NodePtr erase(NodePtr root, int key) {
    NodePtr result = NM.make_node(root);
    NodePtr node = result;
    int left = 0;
    int right = n;
    while (right - left > 1) {
        assert(node);
        // assert(node->value > 0);
        node->value--;
        int mid = (left + right) / 2;
        if (left <= key && key < mid) {
            if (node->left) {
                node->left = NM.make_node(node->left);
            } else {
                node->left = NM.make_node();
            }
            node = node->left;
            right = mid;
        } else {
            if (node->right) {
                node->right = NM.make_node(node->right);
            } else {
                node->right = NM.make_node();
            }
            node = node->right;
            left = mid;
        }
    }
    assert(key == left);
    // assert(node->value == 1);
    node->value--;
    return result;
}

int prod(NodePtr root, int left, int right) {
    auto dfs = [&](auto self, NodePtr node, int l, int r) -> int {
        if (!node) return 0;
        if (left <= l && r <= right) {
            return node->value;
        } else if (r <= left || right <= l) {
            return 0;
        } else {
            int m = (l + r) / 2;
            return self(self, node->left, l, m) + self(self, node->right, m, r);
        }
    };
    return dfs(dfs, root, 0, n);
}

int main() {
    std::cin >> n;
    std::vector<int> a(n);
    for (int i = 0; i < n; i++) std::cin >> a[i];
    {
        auto b = a;
        std::sort(b.begin(), b.end());
        for (int i = 0; i < n; i++) {
            a[i] = std::distance(b.begin(), std::lower_bound(b.begin(), b.end(), a[i]));
        }
    }


    int q;
    std::cin >> q;
    std::vector<std::tuple<int, int, int, int>> query;
    query.reserve(q);
    {
        auto b = a;
        for (int i = 0; i < q; i++) {
            int u, v;
            std::cin >> u >> v;
            u--; v--;
            query.emplace_back(u, v, b[u], b[v]);
            std::swap(b[u], b[v]);
        }
    }

    std::vector<NodePtr> roots(n);
    auto init = [&]() {
        NM.init();
        roots[0] = NM.make_node();
        for (int i = 0; i + 1 < n; i++) {
            roots[i + 1] = insert(roots[i], a[i]);
        }
        long long inv = 0;
        for (int i = 0; i < n; i++) {
            inv += prod(roots[i], a[i], n);
        }
        return inv;
    };

    const int B = 1000;
    // 次に処理すべきクエリ番号
    std::vector<int> last_update(n);
    long long ans = 0;
    for (int t = 0; t < q; t++) {
        if (t % B == 0 || NM.limit()) {
            ans = init();
            last_update.assign(n, t);
        }
        auto [u, v, lv, rv] = query[t];

        // 1. 遅延していたswap処理を行う
        for (auto i: {u, v}) {
            for (; last_update[i] < t; last_update[i]++) {
                int cur = last_update[i];
                auto [p, q, lhs, rhs] = query[cur];
                if (p < i) {
                    roots[i] = insert(erase(roots[i], lhs), rhs);
                }
                if (q < i) {
                    roots[i] = insert(erase(roots[i], rhs), lhs);
                }
            }
        }

        auto contribute = [&](int pos) {
            int left_large = prod(roots[pos], a[pos], n);
            int left_small = (pos - left_large);
            int right_small = a[pos] - left_small;
            return left_large + right_small;
        };

        // 2. 寄与を削除
        ans -= contribute(u) + contribute(v);
        if (a[u] > a[v]) ans++;

        // 3. swap, swapによる寄与を追加
        std::swap(a[u], a[v]);
        ans += contribute(u);
        roots[v] = insert(erase(roots[v], lv), rv);
        ans += contribute(v);
        if (a[u] > a[v]) ans--;

        last_update[u] = t + 1;
        last_update[v] = t + 1;
        assert(a[u] == rv);
        assert(a[v] == lv);

        std::cout << ans << '\n';
    }
}
accuracy: 0.7
time_ms: 1560
memory_kb: 8320
final_rank: 15

code_snippet: #include<bits/stdc++.h>
#define overload(a,b,c,d,...) d
#define rep1(a) for(ll _=0;_<a;++_)
#define rep2(i,a) for(ll i=0;i<a;++i)
#define rep3(i,a,b) for(ll i=a;i<b;++i)
#define rep(...) overload(__VA_ARGS__,rep3,rep2,rep1)(__VA_ARGS__)
#define rrep1(i,a) for(ll i=(ll)a-1;i>=0;--i)
#define rrep2(i,a,b) for(ll i=(ll)b-1;i>=(ll)a;--i)
#define rrep(...) overload(__VA_ARGS__,rrep2,rrep1)(__VA_ARGS__)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define eb emplace_back
#define pb push_back
using namespace std;
using ll=long long;
using ull=unsigned long long;
using ld=long double;
template<typename T,typename U>inline bool chmin(T&a,const U&b){return (a>b?a=b,true:false);}
template<typename T,typename U>inline bool chmax(T&a,const U&b){return (a<b?a=b,true:false);}
static constexpr ll inf=numeric_limits<ll>::max()/2;
/*
ll calc(ll x1,ll y1,ll x2,ll y2,ll x3,ll y3){
    return abs((x1-x3)*(y2-y3)-(x2-x3)*(y1-y3));
}
int main(){
    ll n;cin>>n;
    vector<ll>x(n),y(n);
    rep(i,n)cin>>x[i]>>y[i];
    ll area=0;
    rep(i,1,n-1){
        area+=calc(x[0],y[0],x[i],y[i],x[i+1],y[i+1]);
    }
    ll l=0,r=2;
    ll now=calc(x[0],y[0],x[1],y[1],x[2],y[2]);
    ll ans=abs(area-now*2);
    while(l<n){
        if(now>area/2){
            chmin(ans,abs(area-now*2));
            now-=calc(x[l],y[l],x[(l+1)%n],y[(l+1)%n],x[r],y[r]);
            l++;
            l%=n;
            if((r-l+n)%3==1){
                now+=calc(x[l],y[l],x[r],y[r],x[(r+1)%n],y[(r+1)%n]);
                r++;
                r%=n;
            }
            if(l==0)break;
        }
        chmin(ans,abs(area-now*2));
        now+=calc(x[l],y[l],x[r],y[r],x[(r+1)%n],y[(r+1)%n]);
        r++;
        r%=n;
    }
    cout<<fixed<<setprecision(12)<<ans/2.0<<endl;
}*/
struct BIT{
    private:
    int n;
    vector<int>bit;
    public:
    BIT(int n_):n(n_),bit(n_+1){}
    void add(int i,ll x){
        i++;
        while(i<=n){
            bit[i]+=x;
            i+=i&-i;
        }
    }
    int sum(int k)const{
        ll res=0;
        while(k){
            res+=bit[k];
            k-=k&-k;
        }
        return res;
    }
    int sum(int l,int r)const{return sum(r)-sum(l);}
};
static constexpr ll block_size=2000;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    ll n;cin>>n;
    vector<ll>a(n);
    for(auto&e:a)cin>>e;
    auto b=a;
    sort(all(b));
    b.erase(unique(all(b)),b.end());
    //cout<<b.size()<<endl;
    rep(i,n)a[i]=lower_bound(all(b),a[i])-b.begin();
    vector<BIT>vec((n+block_size-1)/block_size,BIT(b.size()));
    BIT bit(b.size());
    ll ans=0;
    rep(i,n){
        ans+=bit.sum(a[i]+1,b.size());
        bit.add(a[i],1);
        ll now=i/block_size;
        vec[now].add(a[i],1);
    }
    ll m;cin>>m;
    rep(i,m){
        ll l,r;cin>>l>>r;
        l--,r--;
        ll now=l/block_size;
        rep(j,now){
            ans-=vec[j].sum(a[l]+1,b.size());
            ans+=vec[j].sum(a[r]+1,b.size());
        }
        rep(j,now*block_size,l){
            if(a[j]>a[l])ans--;
            if(a[j]>a[r])ans++;
        }
        rep(j,l+1,min(n,(now+1)*block_size)){
            if(a[j]<a[l])ans--;
            if(a[j]<a[r])ans++;
        }
        rep(j,now+1,vec.size()){
            ans-=vec[j].sum(a[l]);
            ans+=vec[j].sum(a[r]);
        }
        //cerr<<ans<<endl;
        vec[now].add(a[l],-1);
        vec[now].add(a[r],1);
        ll tmpl=a[l],tmpr=a[r];
        a[l]=tmpr;
        now=r/block_size;
        rep(j,now){
            ans-=vec[j].sum(a[r]+1,b.size());
            ans+=vec[j].sum(tmpl+1,b.size());
        }
        rep(j,now*block_size,r){
            if(a[j]>a[r])ans--;
            if(a[j]>tmpl)ans++;
        }
        rep(j,r+1,min(n,(now+1)*block_size)){
            if(a[j]<a[r])ans--;
            if(a[j]<tmpl)ans++;
        }
        rep(j,now+1,vec.size()){
            ans-=vec[j].sum(a[r]);
            ans+=vec[j].sum(tmpl);
        }
        vec[now].add(a[r],-1);
        vec[now].add(tmpl,1);
        a[r]=tmpl;
        cout<<ans<<endl;
    }
}
accuracy: 1
time_ms: 2100
memory_kb: 501920
final_rank: 9

code_snippet: #include <bits/stdc++.h>

using ll = long long;

template <class T> using Vec = std::vector<T>;

void make_unique(std::vector<int>& v) {
    std::sort(v.begin(), v.end());
    v.erase(std::unique(v.begin(), v.end()), v.end());
}

int lowb(const std::vector<int>& v, int x) {
    return std::distance(v.begin(), std::lower_bound(v.begin(), v.end(), x));
}

struct Fenwick {
    int n;
    Vec<int> data;
    Fenwick() {}
    Fenwick(int n): n(n), data(n + 1) {}
    void add(int i, int v) {
        i += 1;
        while (i <= n) {
            data[i] += v;
            i += i & -i;
        }
    }
    int get(int i) const {
        int v = 0;
        while (i > 0) {
            v += data[i];
            i -= i & -i;
        }
        return v;
    }
    int fold(int l, int r) const {
        return get(r) - get(l);
    }
};

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n;
    std::cin >> n;
    Vec<int> a(n);
    for (auto& x : a) {
        std::cin >> x;
    }
    int q;
    std::cin >> q;
    Vec<std::pair<int, int>> swap(q);
    for (auto& [x, y] : swap) {
        std::cin >> x >> y;
        x -= 1, y -= 1;
    }
    {
        auto cmp = a;
        make_unique(cmp);
        for (auto& x : a) {
            x = lowb(cmp, x);
        }
    }
    Vec<Vec<int>> appear(n + 1);
    Vec<Fenwick> fen(n + 1);
    {
        auto add = [&](int x, int y) {
            x += 1;
            while (x <= n) {
                appear[x].push_back(y);
                x += x & -x;
            }
        };
        for (int i = 0; i < n; ++i) {
            add(i, a[i]);
        }
        auto a2 = a;
        for (const auto& [x, y] : swap) {
            std::swap(a2[x], a2[y]);
            add(x, a2[x]);
            add(y, a2[y]);
        }
        for (int i = 1; i <= n; ++i) {
            make_unique(appear[i]);
            fen[i] = Fenwick((int)appear[i].size());
        }
    }
    const auto add = [&](int x, int y, int v) {
        x += 1;
        while (x <= n) {
            fen[x].add(lowb(appear[x], y), v);
            x += x & -x;
        }
    };
    const auto get = [&](int x, int l, int r) {
        int v = 0;
        while (x > 0) {
            v += fen[x].fold(lowb(appear[x], l), lowb(appear[x], r));
            x -= x & -x;
        }
        return v;
    };
    ll ans = 0;
    {
        Fenwick tmp(n);
        for (int i = 0; i < n; ++i) {
            ans += tmp.fold(a[i] + 1, n);
            tmp.add(a[i], 1);
        }
    }
    for (int i = 0; i < n; ++i) {
        add(i, a[i], 1);
    }
    for (const auto& [x, y] : swap) {
        if (a[x] < a[y]) {
            ans += 2 * (get(y, a[x], a[y]) - get(x + 1, a[x], a[y])) + 1;
        } else {
            ans -= 2 * (get(y, a[y], a[x]) - get(x + 1, a[y], a[x])) + 1;
        }
        std::cout << ans << '\n';
        add(x, a[x], -1);
        add(y, a[y], -1);
        std::swap(a[x], a[y]);
        add(x, a[x], 1);
        add(y, a[y], 1);
    }
    return 0;
}
accuracy: 1
time_ms: 860
memory_kb: 109304
final_rank: 2

code_snippet: #pragma GCC target("avx2")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;


const int MAX = 500000;
int N, Q;
int a[MAX];
int bit[MAX + 1];
void add(int i, int x) {
    for (i++; i <= MAX; i += i & -i) bit[i] += x;
}
int sum(int i) {
    int ans = 0;
    for (; i; i -= i & -i) ans += bit[i];
    return ans;
}
int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cin >> N;
    for(int i = 0; i < N; i++) cin >> a[i];
    vector<int> idx(N);
    iota(idx.begin(), idx.end(), 0);
    sort(idx.begin(), idx.end(), [](int x, int y){ return a[x] < a[y]; });
    int64_t ans = 0;
    for(int i = N; i--; ){
        ans += sum(idx[i]);
        add(idx[i], 1);
    }
    cin >> Q;
    while(Q--){
        int x, y;
        cin >> x >> y;
        x--; y--;
        if(a[x] < a[y]){
            int cnt = 0;
            for(int i = x + 1; i < y; i++) cnt += a[x] < a[i] && a[i] < a[y];
            ans += cnt * 2 + 1;
        }
        else{
            int cnt = 0;
            for(int i = x + 1; i < y; i++) cnt += a[y] < a[i] && a[i] < a[x];
            ans -= cnt * 2 + 1;
        }
        swap(a[x], a[y]);
        cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 1340
memory_kb: 9032
final_rank: 3

code_snippet: #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;


const int MAX = 500000;
int N, Q;
int a[MAX];
int bit[MAX + 1];
void add(int i, int x) {
    for (i++; i <= MAX; i += i & -i) bit[i] += x;
}
int sum(int i) {
    int ans = 0;
    for (; i; i -= i & -i) ans += bit[i];
    return ans;
}
int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cin >> N;
    for(int i = 0; i < N; i++) cin >> a[i];
    vector<int> idx(N);
    iota(idx.begin(), idx.end(), 0);
    sort(idx.begin(), idx.end(), [](int x, int y){ return a[x] < a[y]; });
    int64_t ans = 0;
    for(int i = N; i--; ){
        ans += sum(idx[i]);
        add(idx[i], 1);
    }
    cin >> Q;
    while(Q--){
        int x, y;
        cin >> x >> y;
        x--; y--;
        if(a[x] < a[y]){
            ans++;
            for(int i = x + 1; i < y; i++) if(a[x] < a[i] && a[i] < a[y]) ans += 2;
        }
        else{
            ans--;
            for(int i = x + 1; i < y; i++) if(a[y] < a[i] && a[i] < a[x]) ans -= 2;
        }
        swap(a[x], a[y]);
        cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 2200
memory_kb: 8936
final_rank: 6

code_snippet: #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;


const int MAX = 500000;
int N, Q;
int a[MAX];
int bit[MAX + 1];
void add(int i, int x) {
    for (i++; i <= MAX; i += i & -i) bit[i] += x;
}
int sum(int i) {
    int ans = 0;
    for (; i; i -= i & -i) ans += bit[i];
    return ans;
}
int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cin >> N;
    for(int i = 0; i < N; i++) cin >> a[i];
    vector<int> idx(N);
    iota(idx.begin(), idx.end(), 0);
    sort(idx.begin(), idx.end(), [](int x, int y){ return a[x] < a[y]; });
    int64_t ans = 0;
    for(int i = N; i--; ){
        ans += sum(idx[i]);
        add(idx[i], 1);
    }
    cin >> Q;
    while(Q--){
        int x, y;
        cin >> x >> y;
        x--; y--;
        if(a[x] < a[y]){
            int cnt = 0;
            for(int i = x + 1; i < y; i++) cnt += a[x] < a[i] && a[i] < a[y];
            ans += cnt * 2 + 1;
        }
        else{
            int cnt = 0;
            for(int i = x + 1; i < y; i++) cnt += a[y] < a[i] && a[i] < a[x];
            ans -= cnt * 2 + 1;
        }
        swap(a[x], a[y]);
        cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 1350
memory_kb: 9028
final_rank: 4

code_snippet: #include <bits/stdc++.h>

// https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=4063729#1
struct dynamic_bitvector {


  struct node;
  using size_type = std::size_t;
  using height_type = long long;
  using node_type = std::unique_ptr<struct node>;
  using node_reference = const node_type&;
  using bits_type = std::uint64_t;
  using children_type = std::array<node_type, 2>;


  const static size_type bit_limit = 32;

  struct bitvector_builder {
    const static size_type bit_size = bit_limit * 2;
    const size_type len;
    std::vector<bits_type> bits;
    bitvector_builder(size_type len): len(len), bits(len / bit_size + !!(len & (bit_size - 1))) {}
    void set(size_type i) { bits[i / bit_size] |= (bits_type(1) << (i & (bit_size - 1))); }
    dynamic_bitvector build() const {
      return dynamic_bitvector(bits, len);
    }
  };

  static size_type bits_popcount(bits_type bits) {
    return __builtin_popcountll(bits);
  }

  struct section_t {
    height_type he;
    children_type ch;
  };

  struct leaf_t {
    bits_type bits;
  };

  union info_t {
    section_t section;
    leaf_t leaf;
    info_t(section_t sec): section(std::move(sec)) {}
    info_t(leaf_t leaf): leaf(leaf) {}
    ~info_t() {}
  };

  struct node {
    const bool is_leaf;
    size_type sz;
    size_type popcnt;
    info_t info;

    static node_type new_section(node_type left, node_type right) {
      node* n = new node(section_t { 0, children_type { std::move(left), std::move(right) } });
      n->fix();
      return node_type(n);
    }

    static node_type new_leaf(bits_type bits, size_type sz, size_type popcnt) {
      node* n = new node(leaf_t { bits });
      n->sz = sz;
      n->popcnt = popcnt;
      return node_type(n);
    }

    node(section_t sec): is_leaf(false), info(std::move(sec)) {}
    node(leaf_t leaf): is_leaf(true), info(leaf) {}

    height_type height() const {
      if(is_leaf) return 0;
      else return info.section.he;
    }
    size_type size() const {
      return sz;
    }

    size_type popcount() const {
      return popcnt;
    }

    // operation for only section node

    node_type take(size_type dir) {
      assert(!is_leaf);
      return std::move(info.section.ch[dir]);
    }

    node_type swap(size_type dir, node_type new_node) {
      assert(!is_leaf);
      node_type old_node = take(dir);
      info.section.ch[dir] = std::move(new_node);
      return old_node;
    }

    const node_type& child(size_type dir) const {
      assert(!is_leaf);
      return info.section.ch[dir];
    }

    height_type diff() const {
      assert(!is_leaf);
      return child(0)->height() - child(1)->height();
    }

    void fix() {
      assert(!is_leaf);
      sz = child(0)->size() + child(1)->size();
      popcnt = child(0)->popcount() + child(1)->popcount();
      info.section.he = std::max(child(0)->height(), child(1)->height()) + 1;
    }

    // operation for only leaf node

    bits_type bits() const {
      assert(is_leaf);
      return info.leaf.bits;
    }

    bool at_bits(size_type pos) const {
      assert(is_leaf);
      return (bits() >> pos) & 1;
    }

    size_type rank(size_type pos) const {
      assert(pos <= size());
      return bits_popcount(bits() & ((bits_type(1) << pos) - 1));
    }

    void set_bits(bits_type bits, size_type sz_, size_type popcnt_) {
      assert(is_leaf);
      sz = sz_;
      popcnt = popcnt_;
      info.leaf.bits = bits;
    }

    // [0, pos) and [pos, sz)
    std::pair<bits_type, bits_type> split_bits(size_type pos) const {
      assert(is_leaf);
      assert(pos <= size());
      return std::make_pair(bits() & ((bits_type(1) << pos) - 1), bits() >> pos);
    }

    void insert_bit(size_type pos, bool bit) {
      assert(is_leaf);
      assert(sz < bit_limit * 2);
      bits_type l, r;
      std::tie(l, r) = split_bits(pos);
     // std::cout << "insert " << bit  << " to " << pos << std::endl;
     // std::cout << "insert " << std::bitset<bit_limit * 2>(l) << " " << std::bitset<bit_limit * 2>(r) << std::endl;
     // std::cout << "insert " << std::bitset<bit_limit * 2>(bits()) << " -> " << std::bitset<bit_limit * 2>(l | ((bits_type(bit) << pos)) | (r << (pos + 1))) << std::endl;
      set_bits(l | ((bits_type(bit) << pos)) | (r << (pos + 1)), sz + 1, popcount() + bit);
    }

    void erase_bit(size_type pos) {
      assert(is_leaf);
      assert(0 < sz);
      bits_type l, r;
      std::tie(l, r) = split_bits(pos);
      size_type pos_bit = r & 1;
      r >>= 1;
      set_bits(l | (r << pos), sz - 1, popcount() - pos_bit);
    }
  };


  static node_type rotate(node_type x, size_type dir) {
    node_type y = x->take(1 - dir);
    node_type b = y->take(dir);
    x->swap(1 - dir, std::move(b));
    x->fix();
    y->swap(dir, std::move(x));
    y->fix();
    return std::move(y);
  }

  static node_type balance(node_type node) {
    node->fix();
    if(node->diff() == 2) {
      if(node->child(0)->diff() == -1) {
        auto ch = node->take(0);
        node->swap(0, rotate(std::move(ch), 0));
      }
      return rotate(std::move(node), 1);
    }
    else if(node->diff() == -2) {
      if(node->child(1)->diff() == 1) {
        auto ch = node->take(1);
        node->swap(1, rotate(std::move(ch), 1));
      }
      return rotate(std::move(node), 0);
    }
    else return std::move(node);
  }

  static node_type split_node(node_type node) {
    assert(node->is_leaf);
    bits_type l, r;
    std::tie(l, r) = node->split_bits(bit_limit);
    return node::new_section(
        node::new_leaf(l, bit_limit, bits_popcount(l)), node::new_leaf(r, node->size() - bit_limit, bits_popcount(r))
        );
  }

  static node_type insert(node_type node, size_type pos, bool bit) {
    if(node->is_leaf) {
      if(node->size() == 2 * bit_limit) {
        return insert(split_node(std::move(node)), pos, bit);
      }
      else {
        node->insert_bit(pos, bit);
        return node;
      }
    }
    else if(pos < node->child(0)->size()) {
      node->swap(0, insert(node->take(0), pos, bit));
      return balance(std::move(node));
    }
    else {
      node->swap(1, insert(node->take(1), pos - node->child(0)->size(), bit));
      return balance(std::move(node));
    }
  }

  template<const size_type dir>
  static std::tuple<node_type, bits_type, size_type> take_bit(node_type node, size_type len) {
    if(node->is_leaf) {
      if(node->size() < bit_limit / 2 + len) {
        return std::tuple<node_type, bits_type, size_type>{ node_type(nullptr), node->bits(), node->size() };
      }
      else {
        auto p = node->split_bits(dir == 0 ? len : node->size() - len);
        bits_type node_bit = std::get<1 - dir>(p);
        bits_type take = std::get<dir>(p);
        node->set_bits(node_bit, node->size() - len, bits_popcount(node_bit));
        return std::tuple<node_type, bits_type, size_type> { std::move(node), take, len };
      }
    }
    else {
      node_type ch;
      bits_type bits;
      size_type take_len;
      std::tie(ch, bits, take_len) = take_bit<dir>(node->take(dir), len);
      if(ch) {
        node->swap(dir, std::move(ch));
        return std::tuple<node_type, bits_type, size_type>{ balance(std::move(node)), bits, take_len };
      }
      else {
        return std::tuple<node_type, bits_type, size_type> { node->take(1 - dir), bits, take_len };
      }
    }
  }

  static node_type erase(node_type node, size_type pos) {
    if(node->is_leaf) {
      node->erase_bit(pos);
      return node;
    }
    else if(pos < node->child(0)->size()) {
      auto left = erase(node->take(0), pos);
      if(left->size() < bit_limit / 2) {
        assert(left->is_leaf);
        node_type right;
        bits_type bits;
        size_type len;
        std::tie(right, bits, len) = take_bit<0>(node->take(1), bit_limit / 2 - left->size());

        left->set_bits(left->bits() | (bits << left->size()), left->size() + len, left->popcount() + bits_popcount(bits));
        if(right) {
          node->swap(0, std::move(left));
          node->swap(1, std::move(right));
          return balance(std::move(node));
        }
        else {
          return left;
        }
      }
      else {
        node->swap(0, std::move(left));
        return balance(std::move(node));
      }
    }
    else {
      auto right = erase(node->take(1), pos - node->child(0)->size());
      if(right->size() < bit_limit / 2) {
        assert(right->is_leaf);
        node_type left;
        bits_type bits;
        size_type len;
        std::tie(left, bits, len) = take_bit<1>(node->take(0), bit_limit / 2 - right->size());

        right->set_bits((right->bits() << len) | bits, right->size() + len, right->popcount() + bits_popcount(bits));
        if(left) {
          node->swap(0, std::move(left));
          node->swap(1, std::move(right));
          return balance(std::move(node));
        }
        else {
          return right;
        }
      }
      else {
        node->swap(1, std::move(right));
        return balance(std::move(node));
      }
    }
  }

  static node_type merge_dir(node_type dst, node_type src, size_type dir) {
    if(std::abs(dst->height() - src->height()) <= 1) {
      if(dir == 0)
        return node::new_section(std::move(src), std::move(dst));
      else
        return node::new_section(std::move(dst), std::move(src));
    }
    else {
      node_type ch = dst->take(dir);
      assert(ch);
      dst->swap(dir, merge_dir(std::move(ch), std::move(src), dir));
      return balance(std::move(dst));
    }
  }

  static node_type merge(node_type left, node_type right) {
    if(!left) { return std::move(right); }
    else if(!right) { return std::move(left); }
    else if(left->height() >= right->height()) {
      return merge_dir(std::move(left), std::move(right), 1);
    }
    else {
      return merge_dir(std::move(right), std::move(left), 0);
    }
  }

  static node_type build(const std::vector<bits_type>& bits, size_type l, size_type r, size_type len) {
    //std::cout << "build " << l << " " << r << " " << len << std::endl;
    if(l + 1 >= r) {
      //std::cout << "create leaf" << std::endl;
      //std::cout << "-----------" << std::endl;
      return node::new_leaf(bits[l], len, bits_popcount(bits[l]));
    }
    else {
      size_type m = (l + r) >> 1;
      return merge(build(bits, l, m, (m - l) * 64), build(bits, m, r, len - (m - l) * 64));
    }
  }

  static size_type at(node_reference node, size_type pos) {
    if(node->is_leaf) {
      return node->at_bits(pos);
    }
    else if(pos < node->child(0)->size()) {
      return at(node->child(0), pos);
    }
    else {
      return at(node->child(1), pos - node->child(0)->size());
    }
  }

  static size_type rank(node_reference node, size_type pos) {
    if(node->is_leaf) {
      return node->rank(pos);
    }
    else if(pos < node->child(0)->size()) {
      return rank(node->child(0), pos);
    }
    else {
      return node->child(0)->popcount() + rank(node->child(1), pos - node->child(0)->size());
    }
  }


  node_type root;

  dynamic_bitvector(): root(node::new_leaf(0, 0, 0)) {}
  dynamic_bitvector(const std::vector<bits_type>& bits, size_type len): root(build(bits, 0, bits.size(), len)) {}
  void insert(size_type pos, bool bit) {
    root = insert(std::move(root), pos, bit);
  }
  void erase(size_type pos) {
    root = erase(std::move(root), pos);
  }
  bool at(size_type pos) const {
    return at(root, pos);
  }
  size_type rank(size_type pos) const {
    return rank(root, pos);
  }
  size_type rank(size_type pos, bool bit) const {
    if(bit) {
      return rank(root, pos);
    }
    else {
      return pos - rank(root, pos);
    }
  }
  size_type size() const {
    return root->size();
  }

  void debug_tree(node_reference node, std::string d) const {
    if(node->is_leaf) {
      std::cout << d << "leaf " << node->size() << " " << node->popcount() << " -----------" << std::endl;
      std::cout << d << std::bitset<bit_limit * 2>(node->bits()) << std::endl;
      std::cout << d << "-------------" << std::endl;
    }
    else {
      std::cout << d << "node " << node->size() << " " << node->popcount() << " ----------" << std::endl;
      std::cout << d << "left" << std::endl;
      debug_tree(node->child(0), d + "   ");
      std::cout << d << "--------------" << std::endl;
      std::cout << d << "right" << std::endl;
      debug_tree(node->child(1), d + "   ");
      std::cout << d << "--------------" << std::endl;
    }
  }

  void debug_tree() const {
    debug_tree(root, "");
  }
};

#include <vector>
struct dynamic_wavelet_matrix {
  using Integer = std::size_t;
  using integer_type = Integer;
  using size_type = std::size_t;


  const size_type depth;
  const size_type len;
  std::vector<dynamic_bitvector> mat;
  std::vector<size_type> spl;

public:

  dynamic_wavelet_matrix(const std::vector<integer_type>& arr, size_type de)
    : depth(de),
      mat(de),
      len(arr.size()),
      spl(std::vector<size_type>(depth, 0)) {
        std::vector<size_type> idx(len);
        std::vector<size_type> left(len), right(len);

        for(size_type i = 0;i < len;i++) idx[i] = i;

        for(size_type d = depth; d-- > 0;) {
          size_type l = 0, r = 0;
          dynamic_bitvector::bitvector_builder builder(len);
          for(size_type i = 0; i < len; i++) {
            size_type k = (arr[idx[i]] >> d) & 1;
            if(k) right[r++] = idx[i], builder.set(i);
            else left[l++] = idx[i];
          }
          mat[d] = builder.build();
          spl[d] = l;
          swap(idx, left);
          for(size_type i = 0; i < r; i++) idx[i + l] = right[i];
        }
      }

  void insert(size_type i, integer_type x) {
    for(size_type d = depth; d --> 0;) {
      size_type k = ((x >> d) & 1);
      mat[d].insert(i, k);
      i = mat[d].rank(i, k) + spl[d] * k;
      if(k == 0) spl[d]++;
    }
  }

  void erase(size_type i) {
    for(size_type d = depth; d--> 0;) {
      size_type k = mat[d].at(i);
      mat[d].erase(i);
      i = mat[d].rank(i, k) + spl[d] * k;
      if(k == 0) spl[d]--;
    }
  }

  integer_type at(size_type i) const {
    integer_type x = static_cast<integer_type>(0);
    for(size_type d = depth; d-- > 0;) {
      size_type k = mat[d].at(i);
      x |= (static_cast<integer_type>(k) << d);
      i = mat[d].rank(i, k) + spl[d] * k;
    }
    return x;
  }

  // counting elements that equal to x in range [left, right)
  size_type rank_x(size_type left, size_type right, integer_type x) const {
    for(size_type d = depth; d-- > 0;) {
      size_type k = ((x >> d) & 1);
      left = mat[d].rank(left, k) + spl[d] * k;
      right = mat[d].rank(right, k) + spl[d] * k;
    }
    return right - left;
  }

  // sorted(arr[left..right])[i]
  integer_type quantile(size_type left, size_type right, size_type i) const {
    integer_type x = static_cast<integer_type>(0);
    for(size_type d = depth; d-- > 0;) {
      size_type cnt = mat[d].rank(right, 0) - mat[d].rank(left, 0);
      size_type k = (i < cnt) ? 0 : 1;
      x |= (k << d);
      left = mat[d].rank(left, k) + spl[d] * k;
      right = mat[d].rank(right, k) + spl[d] * k;
    }
    return x;
  }

  struct rank_result {
    size_type le;
    size_type eq;
    size_type mo;
  };

  // couting elements that less than x, equal to x, and more than x in range [left, right)
  rank_result rank_less_eq_more(size_type left, size_type right, integer_type x) const {
    size_type le = 0, mo = 0;
    for(size_type d = depth; d --> 0;) {
      size_type k = (x >> d) & 1;
      size_type l = mat[d].rank(left, 1);
      size_type r = mat[d].rank(right, 1);
      if(k == 0) {
        mo += r - l;
        left -= l;
        right -= r;
      }
      else {
        le += (right - left) - (r - l);
        left = l + spl[d];
        right = r + spl[d];
      }
    }
    return rank_result { le, right - left, mo };
  }

  size_type rangefreq(size_type left, size_type right, integer_type x, integer_type y, integer_type l, size_type d) const {
    integer_type r = l + (1 << d);
    if(x <= l && r <= y) {
      return right - left;
    }
    else if(y <= l || r <= x) {
      return 0;
    }
    else {
      d--;
      size_type lr = mat[d].rank(left, 1);
      size_type rr = mat[d].rank(right, 1);
      return
        rangefreq(left - lr, right - rr, x, y, l, d) +
        rangefreq(lr + spl[d], rr + spl[d], x, y, l + (1 << d), d);
    }
  }

  size_type rangefreq(size_type left, size_type right, integer_type x, integer_type y) const {
    return rangefreq(left, right, x, y, 0, depth);
  }

  size_type rangefreq_count(size_type left, size_type right, integer_type x, integer_type y) const {
    auto p = rank_less_eq_more(left, right, x);
    auto q = rank_less_eq_more(left, right, y);
    return p.eq + p.mo - q.eq - q.mo;
  }
};

using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using uint = unsigned;
using pcc = pair<char, char>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pdd = pair<ld, ld>;
using tuplis = array<ll, 3>;
template<class T> using pq = priority_queue<T, vector<T>, greater<T>>;
const ll LINF=0x1fffffffffffffff;
const ll MINF=0x7fffffffffff;
const int INF=0x3fffffff;
const int MOD=1000000007;
const int MODD=998244353;
const ld DINF=numeric_limits<ld>::infinity();
const ld EPS=1e-9;
const ld PI=3.1415926535897932;
const ll dx[] = {0, 1, 0, -1, 1, -1, 1, -1};
const ll dy[] = {1, 0, -1, 0, 1, 1, -1, -1};
#define overload5(a,b,c,d,e,name,...) name
#define overload4(a,b,c,d,name,...) name
#define overload3(a,b,c,name,...) name
#define rep1(n) for(ll i=0;i<n;++i)
#define rep2(i,n) for(ll i=0;i<n;++i)
#define rep3(i,a,b) for(ll i=a;i<b;++i)
#define rep4(i,a,b,c) for(ll i=a;i<b;i+=c)
#define rep(...) overload4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__)
#define rrep1(n) for(ll i=n;i--;)
#define rrep2(i,n) for(ll i=n;i--;)
#define rrep3(i,a,b) for(ll i=b;i-->(a);)
#define rrep4(i,a,b,c) for(ll i=(a)+((b)-(a)-1)/(c)*(c);i>=(a);i-=c)
#define rrep(...) overload4(__VA_ARGS__,rrep4,rrep3,rrep2,rrep1)(__VA_ARGS__)
#define each1(i,a) for(auto&&i:a)
#define each2(x,y,a) for(auto&&[x,y]:a)
#define each3(x,y,z,a) for(auto&&[x,y,z]:a)
#define each4(w,x,y,z,a) for(auto&&[w,x,y,z]:a)
#define each(...) overload5(__VA_ARGS__,each4,each3,each2,each1)(__VA_ARGS__)
#define all1(i) begin(i),end(i)
#define all2(i,a) begin(i),begin(i)+a
#define all3(i,a,b) begin(i)+a,begin(i)+b
#define all(...) overload3(__VA_ARGS__,all3,all2,all1)(__VA_ARGS__)
#define rall1(i) (i).rbegin(),(i).rend()
#define rall2(i,k) (i).rbegin(),(i).rbegin()+k
#define rall3(i,a,b) (i).rbegin()+a,(i).rbegin()+b
#define rall(...) overload3(__VA_ARGS__,rall3,rall2,rall1)(__VA_ARGS__)
#define sum(...) accumulate(all(__VA_ARGS__),0LL)
#define dsum(...) accumulate(all(__VA_ARGS__),0.0L)
#define Msum(...) accumulate(all(__VA_ARGS__),0_M)
#define elif else if
#define unless(a) if(!(a))
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;in(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__;in(__VA_ARGS__)
#define Sort(a) sort(all(a))
#define Rev(a) reverse(all(a))
#define Uniq(a) sort(all(a));a.erase(unique(all(a)),end(a))
#define vec(type,name,...) vector<type>name(__VA_ARGS__)
#define VEC(type,name,size) vector<type>name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,w) vector<vector<type>>name(h,vector<type>(w));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
template<class T> auto min(const T& a){ return *min_element(all(a)); }
template<class T> auto max(const T& a){ return *max_element(all(a)); }
inline ll popcnt(ull a){ return __builtin_popcountll(a); }
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
template<class T> bool chmin(T& a, const T& b){ if(a > b){ a = b; return 1; } return 0; }
template<class T> bool chmax(T& a, const T& b){ if(a < b){ a = b; return 1; } return 0; }
template<class T, class U> bool chmin(T& a, const U& b){ if(a > T(b)){ a = b; return 1; } return 0; }
template<class T, class U> bool chmax(T& a, const U& b){ if(a < T(b)){ a = b; return 1; } return 0; }
vector<ll> iota(ll n, ll begin = 0){ vector<ll> a(n); iota(a.begin(), a.end(), begin); return a; }
vector<pll> factor(ull x){ vector<pll> ans; for(ull i = 2; i * i <= x; i++) if(x % i == 0){ ans.push_back({i, 1}); while((x /= i) % i == 0) ans.back().second++; } if(x != 1) ans.push_back({x, 1}); return ans; }
vector<ll> divisor(ull x){ vector<ll> ans; for(ull i = 1; i * i <= x; i++) if(x % i == 0) ans.push_back(i); rrep(ans.size() - (ans.back() * ans.back() == x)) ans.push_back(x / ans[i]); return ans; }
template<class T> unordered_map<T, ll> press(vector<T>& a){ Uniq(a); unordered_map<T, ll> ans; rep(a.size()) ans[a[i]] = i; return ans; }
template<class T> auto run_press(const T& a){ vector<pair<remove_const_t<remove_reference_t<decltype(a[0])>>, ll>> ans; each(x, a){ if(ans.empty() || ans.back().first != x) ans.emplace_back(x, 1); else ans.back().second++; } return ans; }
int scan(){ return getchar(); }
void scan(int& a){ scanf("%d", &a); }
void scan(unsigned& a){ scanf("%u", &a); }
void scan(long& a){ scanf("%ld", &a); }
void scan(long long& a){ scanf("%lld", &a); }
void scan(unsigned long long& a){ scanf("%llu", &a); }
void scan(char& a){ do a = getchar(); while(a == ' ' || a == '\n'); }
void scan(float& a){ scanf("%f", &a); }
void scan(double& a){ scanf("%lf", &a); }
void scan(long double& a){ scanf("%Lf", &a); }
void scan(vector<bool>& a){ for(unsigned i = 0; i < a.size(); i++){ int b; scan(b); a[i] = b; } }
void scan(char a[]){ scanf("%s", a); }
void scan(string& a){ cin >> a; }
template<class T> void scan(vector<T>&);
template<class T, size_t size> void scan(array<T, size>&);
template<class T, class L> void scan(pair<T, L>&);
template<class T, size_t size> void scan(T(&)[size]);
template<class T> void scan(vector<T>& a){ for(auto&& i : a) scan(i); }
template<class T> void scan(deque<T>& a){ for(auto&& i : a) scan(i); }
template<class T, size_t size> void scan(array<T, size>& a){ for(auto&& i : a) scan(i); }
template<class T, class L> void scan(pair<T, L>& p){ scan(p.first); scan(p.second); }
template<class T, size_t size> void scan(T (&a)[size]){ for(auto&& i : a) scan(i); }
template<class T> void scan(T& a){ cin >> a; }
void in(){}
template <class... T> void in(T&... a){ (void)initializer_list<int>{ (scan(a), 0)... }; }
void print(){ putchar(' '); }
void print(bool a){ printf("%d", a); }
void print(int a){ printf("%d", a); }
void print(unsigned a){ printf("%u", a); }
void print(long a){ printf("%ld", a); }
void print(long long a){ printf("%lld", a); }
void print(unsigned long long a){ printf("%llu", a); }
void print(char a){ printf("%c", a); }
void print(char a[]){ printf("%s", a); }
void print(const char a[]){ printf("%s", a); }
void print(float a){ printf("%.15f", a); }
void print(double a){ printf("%.15f", a); }
void print(long double a){ printf("%.15Lf", a); }
void print(const string& a){ for(auto&& i : a) print(i); }
template<class T> void print(const complex<T>& a){ if(a.real() >= 0) print('+'); print(a.real()); if(a.imag() >= 0) print('+'); print(a.imag()); print('i'); }
template<class T> void print(const vector<T>&);
template<class T, size_t size> void print(const array<T, size>&);
template<class T, class L> void print(const pair<T, L>& p);
template<class T, size_t size> void print(const T (&)[size]);
template<class T> void print(const vector<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T> void print(const deque<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, size_t size> void print(const array<T, size>& a){ print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, class L> void print(const pair<T, L>& p){ print(p.first); putchar(' '); print(p.second); }
template<class T, size_t size> void print(const T (&a)[size]){ print(a[0]); for(auto i = a; ++i != end(a); ){ putchar(' '); print(*i); } }
template<class T> void print(const T& a){ cout << a; }
int out(){ putchar('\n'); return 0; }
template<class T> int out(const T& t){ print(t); putchar('\n'); return 0; }
template<class Head, class... Tail> int out(const Head& head, const Tail&... tail){ print(head); putchar(' '); out(tail...); return 0; }
#ifdef DEBUG
inline ll __lg(ull x){ return 63 - __builtin_clzll(x); }
#define debug(...) { print(#__VA_ARGS__); print(":"); out(__VA_ARGS__); }
#else
#define debug(...) void(0)
#endif
int first(bool i = true){ return out(i?"first":"second"); }
int First(bool i = true){ return out(i?"First":"Second"); }
int yes(bool i = true){ return out(i?"yes":"no"); }
int Yes(bool i = true){ return out(i?"Yes":"No"); }
int No(){ return out("No"); }
int YES(bool i = true){ return out(i?"YES":"NO"); }
int NO(){ return out("NO"); }
int Yay(bool i = true){ return out(i?"Yay!":":("); }
int possible(bool i = true){ return out(i?"possible":"impossible"); }
int Possible(bool i = true){ return out(i?"Possible":"Impossible"); }
int POSSIBLE(bool i = true){ return out(i?"POSSIBLE":"IMPOSSIBLE"); }
void Case(ll i){ printf("Case #%lld: ", i); }



template<class T>
struct SegmentTree{
    virtual T f(const T&, const T&) const = 0;
    const T def_value;
    ll size = 1, rank = 0, expected_size;
    vector<T> data;
    SegmentTree(ll n, const T& def_value): def_value(def_value), expected_size(n){
        while(size < expected_size){
            size *= 2;
            rank++;
        }
        data.assign(size * 2, def_value);
    }
    SegmentTree(const vector<T>& v, const T& def_value): def_value(def_value), expected_size(v.size()){
        while(size < expected_size){
            size *= 2;
            rank++;
        }
        data.assign(size * 2, def_value);
        for(ll i = 0; i < v.size(); i++) data[size + i] = v[i];
        // for(ll i = Base::size; --i;) Base::data[i] = f(Base::data[i * 2], Base::data[i * 2 + 1]);
    }
    T operator[](ll at) const {
        return data[size + at];
    }
    void update(ll at){
        while(at /= 2) data[at] = f(data[at * 2], data[at * 2 + 1]);
    }
    void set(ll at, const T& val){
        at += size;
        data[at] = val;
        update(at);
    }
    void add(ll at, const T& val){
        at += size;
        data[at] += val;
        update(at);
    }
    T get(ll l, ll r) const {
        T L = def_value, R = def_value;
        l += size; r += size;
        for(; l < r; l /= 2, r /= 2){
            if(l & 1) L = f(L, data[l++]);
            if(r & 1) R = f(data[--r], R);
        }
        return f(L, R);
    }
    template<class F> ll find_last(const F& check, ll l = 0) const { // max x  s.t. check(get(l, x)) == true
        if(l == expected_size) return expected_size;
        ll height = 0, at = l + size;
        T val = def_value;
        for(; height <= rank; height++) if(at >> height & 1){
            T val2 = f(val, data[at >> height]);
            if(check(val2)){
                at += 1 << height;
                if(at == size * 2) return expected_size;
                val = val2;
            }
            else break;
        }
        for(; height--; ){
            T val2 = f(val, data[at >> height]);
            if(check(val2)){
                at += 1 << height;
                if(at == size * 2) return expected_size;
                val = val2;
            }
        }
        return min(at - size, expected_size);
    }
    template<class F> ll find_first(const F& check, ll r) const { // min x  s.t. check(get(x, r)) == true
        if(!r) return 0;
        ll height = 0, at = r + size;
        T val = def_value;
        for(; height <= rank; height++) if(at >> height & 1){
            T val2 = f(val, data[at >> height ^ 1]);
            if(check(val2)){
                at -= 1 << height;
                if(at == size) return 0;
                val = val2;
            }
            else break;
        }
        for(; height--; ){
            T val2 = f(val, data[(at >> height) - 1]);
            if(check(val2)){
                at -= 1 << height;
                if(at == size) return 0;
                val = val2;
            }
        }
        return at - size;
    }
    void clear(){
        for(auto& i : data) i = def_value;
    }
};
template<class T>
struct RSQ : SegmentTree<T>{
    using Base = SegmentTree<T>;
    T f(const T& a, const T& b) const {return a + b;}
    RSQ(ll n, const T& def_value = T()) : Base(n, def_value){}
    RSQ(const vector<T>& v, const T& def_value = T()) : Base(v, def_value){
        for(ll i = Base::size; --i;) Base::data[i] = f(Base::data[i * 2], Base::data[i * 2 + 1]);
    }
};
int main(){
    LL(n);
    VEC(ll,a,n);
    {
        auto b=a;
        auto p=press(b);
        each(x,a)x=p[x];
    }
    dynamic_wavelet_matrix wm(std::vector<std::size_t>(all(a)), 31);
    RSQ<ll>seg(n);
    ll ans=0;
    each(x,a){
        ans+=seg.get(x+1,seg.size);
        seg.set(x,1);
    }
    LL(q);
    rep(q){
        LL(x,y);
        x--;
        y--;
        if(a[x]<a[y])ans+=wm.rangefreq(x+1,y,a[x],a[y])*2+1;
        else ans-=wm.rangefreq(x+1,y,a[y],a[x])*2+1;
        wm.erase(x);
        wm.insert(x,a[y]);
        wm.erase(y);
        wm.insert(y,a[x]);
        swap(a[x],a[y]);
        out(ans);
    }
}
accuracy: 0.6
time_ms: 40
memory_kb: 4272
final_rank: 18

code_snippet: #include <bits/stdc++.h>

// https://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=4063729#1
struct dynamic_bitvector {


  struct node;
  using size_type = std::size_t;
  using height_type = long long;
  using node_type = std::unique_ptr<struct node>;
  using node_reference = const node_type&;
  using bits_type = std::uint64_t;
  using children_type = std::array<node_type, 2>;


  const static size_type bit_limit = 32;

  struct bitvector_builder {
    const static size_type bit_size = bit_limit * 2;
    const size_type len;
    std::vector<bits_type> bits;
    bitvector_builder(size_type len): len(len), bits(len / bit_size + !!(len & (bit_size - 1))) {}
    void set(size_type i) { bits[i / bit_size] |= (bits_type(1) << (i & (bit_size - 1))); }
    dynamic_bitvector build() const {
      return dynamic_bitvector(bits, len);
    }
  };

  static size_type bits_popcount(bits_type bits) {
    return __builtin_popcountll(bits);
  }

  struct section_t {
    height_type he;
    children_type ch;
  };

  struct leaf_t {
    bits_type bits;
  };

  union info_t {
    section_t section;
    leaf_t leaf;
    info_t(section_t sec): section(std::move(sec)) {}
    info_t(leaf_t leaf): leaf(leaf) {}
    ~info_t() {}
  };

  struct node {
    const bool is_leaf;
    size_type sz;
    size_type popcnt;
    info_t info;

    static node_type new_section(node_type left, node_type right) {
      node* n = new node(section_t { 0, children_type { std::move(left), std::move(right) } });
      n->fix();
      return node_type(n);
    }

    static node_type new_leaf(bits_type bits, size_type sz, size_type popcnt) {
      node* n = new node(leaf_t { bits });
      n->sz = sz;
      n->popcnt = popcnt;
      return node_type(n);
    }

    node(section_t sec): is_leaf(false), info(std::move(sec)) {}
    node(leaf_t leaf): is_leaf(true), info(leaf) {}

    height_type height() const {
      if(is_leaf) return 0;
      else return info.section.he;
    }
    size_type size() const {
      return sz;
    }

    size_type popcount() const {
      return popcnt;
    }

    // operation for only section node

    node_type take(size_type dir) {
      assert(!is_leaf);
      return std::move(info.section.ch[dir]);
    }

    node_type swap(size_type dir, node_type new_node) {
      assert(!is_leaf);
      node_type old_node = take(dir);
      info.section.ch[dir] = std::move(new_node);
      return old_node;
    }

    const node_type& child(size_type dir) const {
      assert(!is_leaf);
      return info.section.ch[dir];
    }

    height_type diff() const {
      assert(!is_leaf);
      return child(0)->height() - child(1)->height();
    }

    void fix() {
      assert(!is_leaf);
      sz = child(0)->size() + child(1)->size();
      popcnt = child(0)->popcount() + child(1)->popcount();
      info.section.he = std::max(child(0)->height(), child(1)->height()) + 1;
    }

    // operation for only leaf node

    bits_type bits() const {
      assert(is_leaf);
      return info.leaf.bits;
    }

    bool at_bits(size_type pos) const {
      assert(is_leaf);
      return (bits() >> pos) & 1;
    }

    size_type rank(size_type pos) const {
      assert(pos <= size());
      return bits_popcount(bits() & ((bits_type(1) << pos) - 1));
    }

    void set_bits(bits_type bits, size_type sz_, size_type popcnt_) {
      assert(is_leaf);
      sz = sz_;
      popcnt = popcnt_;
      info.leaf.bits = bits;
    }

    // [0, pos) and [pos, sz)
    std::pair<bits_type, bits_type> split_bits(size_type pos) const {
      assert(is_leaf);
      assert(pos <= size());
      return std::make_pair(bits() & ((bits_type(1) << pos) - 1), bits() >> pos);
    }

    void insert_bit(size_type pos, bool bit) {
      assert(is_leaf);
      assert(sz < bit_limit * 2);
      bits_type l, r;
      std::tie(l, r) = split_bits(pos);
     // std::cout << "insert " << bit  << " to " << pos << std::endl;
     // std::cout << "insert " << std::bitset<bit_limit * 2>(l) << " " << std::bitset<bit_limit * 2>(r) << std::endl;
     // std::cout << "insert " << std::bitset<bit_limit * 2>(bits()) << " -> " << std::bitset<bit_limit * 2>(l | ((bits_type(bit) << pos)) | (r << (pos + 1))) << std::endl;
      set_bits(l | ((bits_type(bit) << pos)) | (r << (pos + 1)), sz + 1, popcount() + bit);
    }

    void erase_bit(size_type pos) {
      assert(is_leaf);
      assert(0 < sz);
      bits_type l, r;
      std::tie(l, r) = split_bits(pos);
      size_type pos_bit = r & 1;
      r >>= 1;
      set_bits(l | (r << pos), sz - 1, popcount() - pos_bit);
    }
  };


  static node_type rotate(node_type x, size_type dir) {
    node_type y = x->take(1 - dir);
    node_type b = y->take(dir);
    x->swap(1 - dir, std::move(b));
    x->fix();
    y->swap(dir, std::move(x));
    y->fix();
    return std::move(y);
  }

  static node_type balance(node_type node) {
    node->fix();
    if(node->diff() == 2) {
      if(node->child(0)->diff() == -1) {
        auto ch = node->take(0);
        node->swap(0, rotate(std::move(ch), 0));
      }
      return rotate(std::move(node), 1);
    }
    else if(node->diff() == -2) {
      if(node->child(1)->diff() == 1) {
        auto ch = node->take(1);
        node->swap(1, rotate(std::move(ch), 1));
      }
      return rotate(std::move(node), 0);
    }
    else return std::move(node);
  }

  static node_type split_node(node_type node) {
    assert(node->is_leaf);
    bits_type l, r;
    std::tie(l, r) = node->split_bits(bit_limit);
    return node::new_section(
        node::new_leaf(l, bit_limit, bits_popcount(l)), node::new_leaf(r, node->size() - bit_limit, bits_popcount(r))
        );
  }

  static node_type insert(node_type node, size_type pos, bool bit) {
    if(node->is_leaf) {
      if(node->size() == 2 * bit_limit) {
        return insert(split_node(std::move(node)), pos, bit);
      }
      else {
        node->insert_bit(pos, bit);
        return node;
      }
    }
    else if(pos < node->child(0)->size()) {
      node->swap(0, insert(node->take(0), pos, bit));
      return balance(std::move(node));
    }
    else {
      node->swap(1, insert(node->take(1), pos - node->child(0)->size(), bit));
      return balance(std::move(node));
    }
  }

  template<const size_type dir>
  static std::tuple<node_type, bits_type, size_type> take_bit(node_type node, size_type len) {
    if(node->is_leaf) {
      if(node->size() < bit_limit / 2 + len) {
        return std::tuple<node_type, bits_type, size_type>{ node_type(nullptr), node->bits(), node->size() };
      }
      else {
        auto p = node->split_bits(dir == 0 ? len : node->size() - len);
        bits_type node_bit = std::get<1 - dir>(p);
        bits_type take = std::get<dir>(p);
        node->set_bits(node_bit, node->size() - len, bits_popcount(node_bit));
        return std::tuple<node_type, bits_type, size_type> { std::move(node), take, len };
      }
    }
    else {
      node_type ch;
      bits_type bits;
      size_type take_len;
      std::tie(ch, bits, take_len) = take_bit<dir>(node->take(dir), len);
      if(ch) {
        node->swap(dir, std::move(ch));
        return std::tuple<node_type, bits_type, size_type>{ balance(std::move(node)), bits, take_len };
      }
      else {
        return std::tuple<node_type, bits_type, size_type> { node->take(1 - dir), bits, take_len };
      }
    }
  }

  static node_type erase(node_type node, size_type pos) {
    if(node->is_leaf) {
      node->erase_bit(pos);
      return node;
    }
    else if(pos < node->child(0)->size()) {
      auto left = erase(node->take(0), pos);
      if(left->size() < bit_limit / 2) {
        assert(left->is_leaf);
        node_type right;
        bits_type bits;
        size_type len;
        std::tie(right, bits, len) = take_bit<0>(node->take(1), bit_limit / 2 - left->size());

        left->set_bits(left->bits() | (bits << left->size()), left->size() + len, left->popcount() + bits_popcount(bits));
        if(right) {
          node->swap(0, std::move(left));
          node->swap(1, std::move(right));
          return balance(std::move(node));
        }
        else {
          return left;
        }
      }
      else {
        node->swap(0, std::move(left));
        return balance(std::move(node));
      }
    }
    else {
      auto right = erase(node->take(1), pos - node->child(0)->size());
      if(right->size() < bit_limit / 2) {
        assert(right->is_leaf);
        node_type left;
        bits_type bits;
        size_type len;
        std::tie(left, bits, len) = take_bit<1>(node->take(0), bit_limit / 2 - right->size());

        right->set_bits((right->bits() << len) | bits, right->size() + len, right->popcount() + bits_popcount(bits));
        if(left) {
          node->swap(0, std::move(left));
          node->swap(1, std::move(right));
          return balance(std::move(node));
        }
        else {
          return right;
        }
      }
      else {
        node->swap(1, std::move(right));
        return balance(std::move(node));
      }
    }
  }

  static node_type merge_dir(node_type dst, node_type src, size_type dir) {
    if(std::abs(dst->height() - src->height()) <= 1) {
      if(dir == 0)
        return node::new_section(std::move(src), std::move(dst));
      else
        return node::new_section(std::move(dst), std::move(src));
    }
    else {
      node_type ch = dst->take(dir);
      assert(ch);
      dst->swap(dir, merge_dir(std::move(ch), std::move(src), dir));
      return balance(std::move(dst));
    }
  }

  static node_type merge(node_type left, node_type right) {
    if(!left) { return std::move(right); }
    else if(!right) { return std::move(left); }
    else if(left->height() >= right->height()) {
      return merge_dir(std::move(left), std::move(right), 1);
    }
    else {
      return merge_dir(std::move(right), std::move(left), 0);
    }
  }

  static node_type build(const std::vector<bits_type>& bits, size_type l, size_type r, size_type len) {
    //std::cout << "build " << l << " " << r << " " << len << std::endl;
    if(l + 1 >= r) {
      //std::cout << "create leaf" << std::endl;
      //std::cout << "-----------" << std::endl;
      return node::new_leaf(bits[l], len, bits_popcount(bits[l]));
    }
    else {
      size_type m = (l + r) >> 1;
      return merge(build(bits, l, m, (m - l) * 64), build(bits, m, r, len - (m - l) * 64));
    }
  }

  static size_type at(node_reference node, size_type pos) {
    if(node->is_leaf) {
      return node->at_bits(pos);
    }
    else if(pos < node->child(0)->size()) {
      return at(node->child(0), pos);
    }
    else {
      return at(node->child(1), pos - node->child(0)->size());
    }
  }

  static size_type rank(node_reference node, size_type pos) {
    if(node->is_leaf) {
      return node->rank(pos);
    }
    else if(pos < node->child(0)->size()) {
      return rank(node->child(0), pos);
    }
    else {
      return node->child(0)->popcount() + rank(node->child(1), pos - node->child(0)->size());
    }
  }


  node_type root;

  dynamic_bitvector(): root(node::new_leaf(0, 0, 0)) {}
  dynamic_bitvector(const std::vector<bits_type>& bits, size_type len): root(build(bits, 0, bits.size(), len)) {}
  void insert(size_type pos, bool bit) {
    root = insert(std::move(root), pos, bit);
  }
  void erase(size_type pos) {
    root = erase(std::move(root), pos);
  }
  bool at(size_type pos) const {
    return at(root, pos);
  }
  size_type rank(size_type pos) const {
    return rank(root, pos);
  }
  size_type rank(size_type pos, bool bit) const {
    if(bit) {
      return rank(root, pos);
    }
    else {
      return pos - rank(root, pos);
    }
  }
  size_type size() const {
    return root->size();
  }

  void debug_tree(node_reference node, std::string d) const {
    if(node->is_leaf) {
      std::cout << d << "leaf " << node->size() << " " << node->popcount() << " -----------" << std::endl;
      std::cout << d << std::bitset<bit_limit * 2>(node->bits()) << std::endl;
      std::cout << d << "-------------" << std::endl;
    }
    else {
      std::cout << d << "node " << node->size() << " " << node->popcount() << " ----------" << std::endl;
      std::cout << d << "left" << std::endl;
      debug_tree(node->child(0), d + "   ");
      std::cout << d << "--------------" << std::endl;
      std::cout << d << "right" << std::endl;
      debug_tree(node->child(1), d + "   ");
      std::cout << d << "--------------" << std::endl;
    }
  }

  void debug_tree() const {
    debug_tree(root, "");
  }
};

#include <vector>
struct dynamic_wavelet_matrix {
  using Integer = std::size_t;
  using integer_type = Integer;
  using size_type = std::size_t;


  const size_type depth;
  const size_type len;
  std::vector<dynamic_bitvector> mat;
  std::vector<size_type> spl;

public:

  dynamic_wavelet_matrix(const std::vector<integer_type>& arr, size_type de)
    : depth(de),
      mat(de),
      len(arr.size()),
      spl(std::vector<size_type>(depth, 0)) {
        std::vector<size_type> idx(len);
        std::vector<size_type> left(len), right(len);

        for(size_type i = 0;i < len;i++) idx[i] = i;

        for(size_type d = depth; d-- > 0;) {
          size_type l = 0, r = 0;
          dynamic_bitvector::bitvector_builder builder(len);
          for(size_type i = 0; i < len; i++) {
            size_type k = (arr[idx[i]] >> d) & 1;
            if(k) right[r++] = idx[i], builder.set(i);
            else left[l++] = idx[i];
          }
          mat[d] = builder.build();
          spl[d] = l;
          swap(idx, left);
          for(size_type i = 0; i < r; i++) idx[i + l] = right[i];
        }
      }

  void insert(size_type i, integer_type x) {
    for(size_type d = depth; d --> 0;) {
      size_type k = ((x >> d) & 1);
      mat[d].insert(i, k);
      i = mat[d].rank(i, k) + spl[d] * k;
      if(k == 0) spl[d]++;
    }
  }

  void erase(size_type i) {
    for(size_type d = depth; d--> 0;) {
      size_type k = mat[d].at(i);
      mat[d].erase(i);
      i = mat[d].rank(i, k) + spl[d] * k;
      if(k == 0) spl[d]--;
    }
  }

  integer_type at(size_type i) const {
    integer_type x = static_cast<integer_type>(0);
    for(size_type d = depth; d-- > 0;) {
      size_type k = mat[d].at(i);
      x |= (static_cast<integer_type>(k) << d);
      i = mat[d].rank(i, k) + spl[d] * k;
    }
    return x;
  }

  // counting elements that equal to x in range [left, right)
  size_type rank_x(size_type left, size_type right, integer_type x) const {
    for(size_type d = depth; d-- > 0;) {
      size_type k = ((x >> d) & 1);
      left = mat[d].rank(left, k) + spl[d] * k;
      right = mat[d].rank(right, k) + spl[d] * k;
    }
    return right - left;
  }

  // sorted(arr[left..right])[i]
  integer_type quantile(size_type left, size_type right, size_type i) const {
    integer_type x = static_cast<integer_type>(0);
    for(size_type d = depth; d-- > 0;) {
      size_type cnt = mat[d].rank(right, 0) - mat[d].rank(left, 0);
      size_type k = (i < cnt) ? 0 : 1;
      x |= (k << d);
      left = mat[d].rank(left, k) + spl[d] * k;
      right = mat[d].rank(right, k) + spl[d] * k;
    }
    return x;
  }

  struct rank_result {
    size_type le;
    size_type eq;
    size_type mo;
  };

  // couting elements that less than x, equal to x, and more than x in range [left, right)
  rank_result rank_less_eq_more(size_type left, size_type right, integer_type x) const {
    size_type le = 0, mo = 0;
    for(size_type d = depth; d --> 0;) {
      size_type k = (x >> d) & 1;
      size_type l = mat[d].rank(left, 1);
      size_type r = mat[d].rank(right, 1);
      if(k == 0) {
        mo += r - l;
        left -= l;
        right -= r;
      }
      else {
        le += (right - left) - (r - l);
        left = l + spl[d];
        right = r + spl[d];
      }
    }
    return rank_result { le, right - left, mo };
  }

  size_type rangefreq(size_type left, size_type right, integer_type x, integer_type y, integer_type l, size_type d) const {
    integer_type r = l + (1 << d);
    if(x <= l && r <= y) {
      return right - left;
    }
    else if(y <= l || r <= x) {
      return 0;
    }
    else {
      d--;
      size_type lr = mat[d].rank(left, 1);
      size_type rr = mat[d].rank(right, 1);
      return
        rangefreq(left - lr, right - rr, x, y, l, d) +
        rangefreq(lr + spl[d], rr + spl[d], x, y, l + (1 << d), d);
    }
  }

  size_type rangefreq(size_type left, size_type right, integer_type x, integer_type y) const {
    return rangefreq(left, right, x, y, 0, depth);
  }

  size_type rangefreq_count(size_type left, size_type right, integer_type x, integer_type y) const {
    auto p = rank_less_eq_more(left, right, x);
    auto q = rank_less_eq_more(left, right, y);
    return p.eq + p.mo - q.eq - q.mo;
  }
};

using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using uint = unsigned;
using pcc = pair<char, char>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pdd = pair<ld, ld>;
using tuplis = array<ll, 3>;
template<class T> using pq = priority_queue<T, vector<T>, greater<T>>;
const ll LINF=0x1fffffffffffffff;
const ll MINF=0x7fffffffffff;
const int INF=0x3fffffff;
const int MOD=1000000007;
const int MODD=998244353;
const ld DINF=numeric_limits<ld>::infinity();
const ld EPS=1e-9;
const ld PI=3.1415926535897932;
const ll dx[] = {0, 1, 0, -1, 1, -1, 1, -1};
const ll dy[] = {1, 0, -1, 0, 1, 1, -1, -1};
#define overload5(a,b,c,d,e,name,...) name
#define overload4(a,b,c,d,name,...) name
#define overload3(a,b,c,name,...) name
#define rep1(n) for(ll i=0;i<n;++i)
#define rep2(i,n) for(ll i=0;i<n;++i)
#define rep3(i,a,b) for(ll i=a;i<b;++i)
#define rep4(i,a,b,c) for(ll i=a;i<b;i+=c)
#define rep(...) overload4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__)
#define rrep1(n) for(ll i=n;i--;)
#define rrep2(i,n) for(ll i=n;i--;)
#define rrep3(i,a,b) for(ll i=b;i-->(a);)
#define rrep4(i,a,b,c) for(ll i=(a)+((b)-(a)-1)/(c)*(c);i>=(a);i-=c)
#define rrep(...) overload4(__VA_ARGS__,rrep4,rrep3,rrep2,rrep1)(__VA_ARGS__)
#define each1(i,a) for(auto&&i:a)
#define each2(x,y,a) for(auto&&[x,y]:a)
#define each3(x,y,z,a) for(auto&&[x,y,z]:a)
#define each4(w,x,y,z,a) for(auto&&[w,x,y,z]:a)
#define each(...) overload5(__VA_ARGS__,each4,each3,each2,each1)(__VA_ARGS__)
#define all1(i) begin(i),end(i)
#define all2(i,a) begin(i),begin(i)+a
#define all3(i,a,b) begin(i)+a,begin(i)+b
#define all(...) overload3(__VA_ARGS__,all3,all2,all1)(__VA_ARGS__)
#define rall1(i) (i).rbegin(),(i).rend()
#define rall2(i,k) (i).rbegin(),(i).rbegin()+k
#define rall3(i,a,b) (i).rbegin()+a,(i).rbegin()+b
#define rall(...) overload3(__VA_ARGS__,rall3,rall2,rall1)(__VA_ARGS__)
#define sum(...) accumulate(all(__VA_ARGS__),0LL)
#define dsum(...) accumulate(all(__VA_ARGS__),0.0L)
#define Msum(...) accumulate(all(__VA_ARGS__),0_M)
#define elif else if
#define unless(a) if(!(a))
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;in(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__;in(__VA_ARGS__)
#define Sort(a) sort(all(a))
#define Rev(a) reverse(all(a))
#define Uniq(a) sort(all(a));a.erase(unique(all(a)),end(a))
#define vec(type,name,...) vector<type>name(__VA_ARGS__)
#define VEC(type,name,size) vector<type>name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,w) vector<vector<type>>name(h,vector<type>(w));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
template<class T> auto min(const T& a){ return *min_element(all(a)); }
template<class T> auto max(const T& a){ return *max_element(all(a)); }
inline ll popcnt(ull a){ return __builtin_popcountll(a); }
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
template<class T> bool chmin(T& a, const T& b){ if(a > b){ a = b; return 1; } return 0; }
template<class T> bool chmax(T& a, const T& b){ if(a < b){ a = b; return 1; } return 0; }
template<class T, class U> bool chmin(T& a, const U& b){ if(a > T(b)){ a = b; return 1; } return 0; }
template<class T, class U> bool chmax(T& a, const U& b){ if(a < T(b)){ a = b; return 1; } return 0; }
vector<ll> iota(ll n, ll begin = 0){ vector<ll> a(n); iota(a.begin(), a.end(), begin); return a; }
vector<pll> factor(ull x){ vector<pll> ans; for(ull i = 2; i * i <= x; i++) if(x % i == 0){ ans.push_back({i, 1}); while((x /= i) % i == 0) ans.back().second++; } if(x != 1) ans.push_back({x, 1}); return ans; }
vector<ll> divisor(ull x){ vector<ll> ans; for(ull i = 1; i * i <= x; i++) if(x % i == 0) ans.push_back(i); rrep(ans.size() - (ans.back() * ans.back() == x)) ans.push_back(x / ans[i]); return ans; }
template<class T> unordered_map<T, ll> press(vector<T>& a){ Uniq(a); unordered_map<T, ll> ans; rep(a.size()) ans[a[i]] = i; return ans; }
template<class T> auto run_press(const T& a){ vector<pair<remove_const_t<remove_reference_t<decltype(a[0])>>, ll>> ans; each(x, a){ if(ans.empty() || ans.back().first != x) ans.emplace_back(x, 1); else ans.back().second++; } return ans; }
int scan(){ return getchar(); }
void scan(int& a){ scanf("%d", &a); }
void scan(unsigned& a){ scanf("%u", &a); }
void scan(long& a){ scanf("%ld", &a); }
void scan(long long& a){ scanf("%lld", &a); }
void scan(unsigned long long& a){ scanf("%llu", &a); }
void scan(char& a){ do a = getchar(); while(a == ' ' || a == '\n'); }
void scan(float& a){ scanf("%f", &a); }
void scan(double& a){ scanf("%lf", &a); }
void scan(long double& a){ scanf("%Lf", &a); }
void scan(vector<bool>& a){ for(unsigned i = 0; i < a.size(); i++){ int b; scan(b); a[i] = b; } }
void scan(char a[]){ scanf("%s", a); }
void scan(string& a){ cin >> a; }
template<class T> void scan(vector<T>&);
template<class T, size_t size> void scan(array<T, size>&);
template<class T, class L> void scan(pair<T, L>&);
template<class T, size_t size> void scan(T(&)[size]);
template<class T> void scan(vector<T>& a){ for(auto&& i : a) scan(i); }
template<class T> void scan(deque<T>& a){ for(auto&& i : a) scan(i); }
template<class T, size_t size> void scan(array<T, size>& a){ for(auto&& i : a) scan(i); }
template<class T, class L> void scan(pair<T, L>& p){ scan(p.first); scan(p.second); }
template<class T, size_t size> void scan(T (&a)[size]){ for(auto&& i : a) scan(i); }
template<class T> void scan(T& a){ cin >> a; }
void in(){}
template <class... T> void in(T&... a){ (void)initializer_list<int>{ (scan(a), 0)... }; }
void print(){ putchar(' '); }
void print(bool a){ printf("%d", a); }
void print(int a){ printf("%d", a); }
void print(unsigned a){ printf("%u", a); }
void print(long a){ printf("%ld", a); }
void print(long long a){ printf("%lld", a); }
void print(unsigned long long a){ printf("%llu", a); }
void print(char a){ printf("%c", a); }
void print(char a[]){ printf("%s", a); }
void print(const char a[]){ printf("%s", a); }
void print(float a){ printf("%.15f", a); }
void print(double a){ printf("%.15f", a); }
void print(long double a){ printf("%.15Lf", a); }
void print(const string& a){ for(auto&& i : a) print(i); }
template<class T> void print(const complex<T>& a){ if(a.real() >= 0) print('+'); print(a.real()); if(a.imag() >= 0) print('+'); print(a.imag()); print('i'); }
template<class T> void print(const vector<T>&);
template<class T, size_t size> void print(const array<T, size>&);
template<class T, class L> void print(const pair<T, L>& p);
template<class T, size_t size> void print(const T (&)[size]);
template<class T> void print(const vector<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T> void print(const deque<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, size_t size> void print(const array<T, size>& a){ print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, class L> void print(const pair<T, L>& p){ print(p.first); putchar(' '); print(p.second); }
template<class T, size_t size> void print(const T (&a)[size]){ print(a[0]); for(auto i = a; ++i != end(a); ){ putchar(' '); print(*i); } }
template<class T> void print(const T& a){ cout << a; }
int out(){ putchar('\n'); return 0; }
template<class T> int out(const T& t){ print(t); putchar('\n'); return 0; }
template<class Head, class... Tail> int out(const Head& head, const Tail&... tail){ print(head); putchar(' '); out(tail...); return 0; }
#ifdef DEBUG
inline ll __lg(ull x){ return 63 - __builtin_clzll(x); }
#define debug(...) { print(#__VA_ARGS__); print(":"); out(__VA_ARGS__); }
#else
#define debug(...) void(0)
#endif
int first(bool i = true){ return out(i?"first":"second"); }
int First(bool i = true){ return out(i?"First":"Second"); }
int yes(bool i = true){ return out(i?"yes":"no"); }
int Yes(bool i = true){ return out(i?"Yes":"No"); }
int No(){ return out("No"); }
int YES(bool i = true){ return out(i?"YES":"NO"); }
int NO(){ return out("NO"); }
int Yay(bool i = true){ return out(i?"Yay!":":("); }
int possible(bool i = true){ return out(i?"possible":"impossible"); }
int Possible(bool i = true){ return out(i?"Possible":"Impossible"); }
int POSSIBLE(bool i = true){ return out(i?"POSSIBLE":"IMPOSSIBLE"); }
void Case(ll i){ printf("Case #%lld: ", i); }



template<class T>
struct SegmentTree{
    virtual T f(const T&, const T&) const = 0;
    const T def_value;
    ll size = 1, rank = 0, expected_size;
    vector<T> data;
    SegmentTree(ll n, const T& def_value): def_value(def_value), expected_size(n){
        while(size < expected_size){
            size *= 2;
            rank++;
        }
        data.assign(size * 2, def_value);
    }
    SegmentTree(const vector<T>& v, const T& def_value): def_value(def_value), expected_size(v.size()){
        while(size < expected_size){
            size *= 2;
            rank++;
        }
        data.assign(size * 2, def_value);
        for(ll i = 0; i < v.size(); i++) data[size + i] = v[i];
        // for(ll i = Base::size; --i;) Base::data[i] = f(Base::data[i * 2], Base::data[i * 2 + 1]);
    }
    T operator[](ll at) const {
        return data[size + at];
    }
    void update(ll at){
        while(at /= 2) data[at] = f(data[at * 2], data[at * 2 + 1]);
    }
    void set(ll at, const T& val){
        at += size;
        data[at] = val;
        update(at);
    }
    void add(ll at, const T& val){
        at += size;
        data[at] += val;
        update(at);
    }
    T get(ll l, ll r) const {
        T L = def_value, R = def_value;
        l += size; r += size;
        for(; l < r; l /= 2, r /= 2){
            if(l & 1) L = f(L, data[l++]);
            if(r & 1) R = f(data[--r], R);
        }
        return f(L, R);
    }
    template<class F> ll find_last(const F& check, ll l = 0) const { // max x  s.t. check(get(l, x)) == true
        if(l == expected_size) return expected_size;
        ll height = 0, at = l + size;
        T val = def_value;
        for(; height <= rank; height++) if(at >> height & 1){
            T val2 = f(val, data[at >> height]);
            if(check(val2)){
                at += 1 << height;
                if(at == size * 2) return expected_size;
                val = val2;
            }
            else break;
        }
        for(; height--; ){
            T val2 = f(val, data[at >> height]);
            if(check(val2)){
                at += 1 << height;
                if(at == size * 2) return expected_size;
                val = val2;
            }
        }
        return min(at - size, expected_size);
    }
    template<class F> ll find_first(const F& check, ll r) const { // min x  s.t. check(get(x, r)) == true
        if(!r) return 0;
        ll height = 0, at = r + size;
        T val = def_value;
        for(; height <= rank; height++) if(at >> height & 1){
            T val2 = f(val, data[at >> height ^ 1]);
            if(check(val2)){
                at -= 1 << height;
                if(at == size) return 0;
                val = val2;
            }
            else break;
        }
        for(; height--; ){
            T val2 = f(val, data[(at >> height) - 1]);
            if(check(val2)){
                at -= 1 << height;
                if(at == size) return 0;
                val = val2;
            }
        }
        return at - size;
    }
    void clear(){
        for(auto& i : data) i = def_value;
    }
};
template<class T>
struct RSQ : SegmentTree<T>{
    using Base = SegmentTree<T>;
    T f(const T& a, const T& b) const {return a + b;}
    RSQ(ll n, const T& def_value = T()) : Base(n, def_value){}
    RSQ(const vector<T>& v, const T& def_value = T()) : Base(v, def_value){
        for(ll i = Base::size; --i;) Base::data[i] = f(Base::data[i * 2], Base::data[i * 2 + 1]);
    }
};
int main(){
    LL(n);
    VEC(ll,a,n);
    {
        auto b=a;
        auto p=press(b);
        each(x,a)x=p[x];
    }
    dynamic_wavelet_matrix wm(std::vector<std::size_t>(all(a)), 31);
    RSQ<ll>seg(n);
    ll ans=0;
    each(x,a){
        ans+=seg.get(x+1,seg.size);
        seg.set(x,1);
    }
    LL(q);
    rep(q){
        LL(x,y);
        x--;
        y--;
        if(a[x]<a[y])ans+=wm.rangefreq(x+1,y,a[x],a[y])*2+1;
        else ans-=wm.rangefreq(x+1,y,a[y],a[x])*2+1;
        wm.erase(x);
        wm.insert(x,a[y]);
        wm.erase(y);
        wm.insert(y,a[x]);
        swap(a[x],a[y]);
        out(ans);
    }
}
accuracy: 0.6
time_ms: 40
memory_kb: 4260
final_rank: 17