先决条件:基于策略的数据结构
给定一个数组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 之前的元素的计数。
- 在基于策略的数据结构 St 中插入当前元素 X 及其索引。索引与每个元素一起插入,用于在集合中唯一标识并处理重复项。
- 对每个元素 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
时间复杂度:
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live