JOI 2013 - Bubblesort

Author: Andi Qu

Intuition

In this problem, we're asked to find the maximum decrease in the number of inversions of the array.

Firstly, unless the array is already sorted, we can always decrease the number of inversions. We can also assume that we only ever swap and () if . (Could you prove this formally?)

After playing around with some swaps and arrays, we find that the only array elements that contribute to that change if we swap and () are the such that and .

This condition feels similar to the inequalities defining a rectangle. Could we possibly find a geometric interpretation of this problem?

Turning the Problem into Geometry

Plot the points on the Cartesian plane.

Notice how if we swap and (), the change in the number of inversions is equal to:

From this, we also find that if we have and , then can't be the left index in the optimal swap.

This means that we can simply consider a set of with strictly increasing as candidates for the left index in the optimal swap!

Using the D&C Optimization

Let be the index such that if we must swap with something to its right, then swapping it with is optimal.

Since is strictly increasing in our set of candidates, we can prove that for all in our set.

This means that we can use the D&C optimization to find all !

We can use a BIT or any other suitable data structure to query the number of points in a rectangle efficiently.

Complexity

Time: .

Memory: .

Code

1#include <bits/stdc++.h>
2#define FOR(i, x, y) for (int i = x; i < y; i++)
3typedef long long ll;
4using namespace std;
5
6ll ans = 0, bit[100001];
7int n, a[100001], b[100001];
8vector<int> cand;
9
10void update(int pos, ll val) {

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

Give Us Feedback on JOI 2013 - Bubblesort!