diff --git a/content/maths.tex b/content/maths.tex index e884ec3..985745b 100644 --- a/content/maths.tex +++ b/content/maths.tex @@ -368,3 +368,9 @@ \subsection{Divide \& Conquer DP optimization} } \end{lstlisting} \snippet{source/dnc_dp_optimization.h} + +\subsection{Count inversions} +\bigo{NlogN} Counts the number of inversions in a 0-based permutation. +An inversion is a swap of two adjacent elements. \\ +Requires \verb|Fenwick| +\snippet{source/inversions.cpp} diff --git a/source/inversions.cpp b/source/inversions.cpp new file mode 100644 index 0000000..2ccc58f --- /dev/null +++ b/source/inversions.cpp @@ -0,0 +1,18 @@ +#pragma once +#include "common.h" +#include "fenwick.h" + +ll inversions(vi p) +{ + int n = ssize(p); + Fenwick ft(n); + vi pos(n); + for(int i=0; i < n; i++) + pos[p[i]] = i; + ll res = 0; + for(int i = 0; i < n; i++) { + res += ft.sum(0, pos[i]); + ft.add(pos[i], -1); + } + return res; +}