By solving this problem I better understand the concept of inversion number (aka inversion count). Let $p$ be a permutation of $N$ distinct elements, and $q$ be another permutation of those elements. The inversion number between $p$ and $q$ is defined as the number of ordered pairs of elements $(x, y)$ such that $x$ is to the left of $y$ in permutation $p$, but $x$ is to the right of $y$ in permutation $q$, or equivalently as the number of ordered pairs of elements $(x, y)$ such that $x$ is to the right of $y$ in permutation $p$, but $x$ is to the left of $y$ in permutation $q$.
The inversion number between $p$ and $q$ is the minimum possible number of operations of swapping two adjacent elements to change $p$ into $q$.
Official tutorial:
code
int main() {
int n;
scan(n);
vi pos_w(n + 1), pos_b(n + 1);
rng (i, 0, 2 * n) {
char color;
int number;
scan(color, number);
if (color == 'B') {
pos_b[number] = i;
} else {
pos_w[number] = i;
}
}
// nb_after[i][j] : number of black balls placed after position i numbered between 1 and j.
// nw_after[i][j] : number of white balls placed after position i numbered between 1 and j.
vv nb_after(2 * n, vi(n + 1)), nw_after(2 * n, vi(n + 1));
rng (i, 0, 2 * n) {
up (j, 1, n) {
nb_after[i][j] = nb_after[i][j - 1] + (pos_b[j] > i);
nw_after[i][j] = nw_after[i][j - 1] + (pos_w[j] > i);
}
}
// dp[i][j] : minimum possible inversion number among first i black balls and first j white balls
vv dp(n + 1, vi(n + 1));
up (i, 1, n) {
dp[i][0] = dp[i - 1][0] + nb_after[pos_b[i]][i - 1];
}
up (i, 1, n) {
dp[0][i] = dp[0][i - 1] + nw_after[pos_w[i]][i - 1];
}
up (i, 1, n) {
up (j, 1, n) {
dp[i][j] = min(dp[i][j - 1] + nb_after[pos_w[j]][i] + nw_after[pos_w[j]][j - 1],
dp[i - 1][j] + nb_after[pos_b[i]][i - 1] + nw_after[pos_b[i]][j]);
}
}
println(dp[n][n]);
return 0;
}