先决条件:基于策略的数据结构
给定一个数组arr [] ,任务是找到该数组每个元素的求反数。
Inversion Count: for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted then the inversion count is 0. If the array is sorted in the reverse order then the inversion count is the maximum.
Formally, Number of indices and such that and .
例子:
Input: {5, 2, 3, 2, 3, 8, 1}
Output: {0, 1, 1, 2, 1, 0, 6}
Explanation:
Inversion count for each elements –
Element at index 0: There are no elements with less index than 0, which is greater than arr[0].
Element at index 1: There is one element with less index than 1, which is greater than 2. That is 5.
Element at index 2: There is one element with less index than 2, which is greater than 3. That is 5.
Element at index 3: There are two elements with less index than 3, which is greater than 2. That is 5, 3.
Element at index 4: There is one element with less index than 4, which is greater than 3. That is 5.
Element at index 5: There are no elements with less index than 5, which is greater than 8.
Element at index 6: There are six elements with less index than 6, which is greater than 1. That is 5, 2, 3, 2, 3
Input: arr[] = {3, 2, 1}
Output: {0, 1, 2}
方法:
- 创建基于策略的类型对数据结构。
- 迭代给定的数组并执行以下步骤–
- 对每个元素X应用order_of_key({X,N + 1}),其中N是数组的大小。
注意: order_of_key只是lower_bound。另外,我们使用N + 1,因为它大于数组中的所有索引。 - 假设order_of_key的结果为l,则当前元素的反转计数等于它最终是小于X且在数组中X之前的元素计数。
- 将当前元素X及其索引插入基于策略的数据结构St中。将索引与每个元素一起插入,以在集合中对其进行唯一标识并处理重复项。
- 对每个元素X应用order_of_key({X,N + 1}),其中N是数组的大小。
下面是上述方法的实现:
C++
// C++ implementation to find the
// Inversion Count using Policy
// Based Data Structure
#include
// Header files for policy based
// data structure which are
// to be included
#include
#include
using namespace __gnu_pbds;
using namespace std;
typedef tree, null_type,
less >, rb_tree_tag,
tree_order_statistics_node_update>
new_data_set;
// Function to find the inversion count
// of the elements of the array
void inversionCount(int arr[], int n)
{
int ans[n];
// Making a new policy based data
// structure which will
// store pair
new_data_set St;
// Loop to iterate over the elements
// of the array
for (int i = 0; i < n; i++) {
// Now to find lower_bound of
// the element X, we will use pair
// as {x, n+1} to cover all the
// elements and even the duplicates
int cur = St.order_of_key({ arr[i],
n + 1 });
ans[i] = St.size() - cur;
// Store element along with index
St.insert({ arr[i], i });
}
for (int i = 0; i < n; i++) {
cout << ans[i] << " ";
}
cout << "\n";
}
// Driver Code
int main()
{
int arr[] = { 5, 2, 3, 2, 3, 8, 1 };
int n = sizeof(arr) / sizeof(int);
// Function Call
inversionCount(arr, n);
return 0;
}
0 1 1 2 1 0 6
时间复杂度: