C++ 如何在数组中找到反转对及其索引位置?
我发现在阵列中很难找到反转对。我得到了数组中反转对的数量,但逻辑似乎太复杂了,我无法列出反转对。我是新的C++,任何帮助都值得赞赏。C++ 如何在数组中找到反转对及其索引位置?,c++,fenwick-tree,C++,Fenwick Tree,我发现在阵列中很难找到反转对。我得到了数组中反转对的数量,但逻辑似乎太复杂了,我无法列出反转对。我是新的C++,任何帮助都值得赞赏。 Example: Input: arr[] = {8, 4, 2, 1} Output: 6 期待这个输出 给定数组有六个逆(8,4)和索引(0,1),(4,2)和索引(1,2), (8,2)和指数(0,2)、(8,1)和指数(0,3)、(4,1)以及指数(1,3)、(2,1)和指数(2,4) 用二进制索引树计算代码翻转的代码> //C++程序 #包括
Example:
Input: arr[] = {8, 4, 2, 1}
Output: 6
期待这个输出
给定数组有六个逆(8,4)和索引(0,1),(4,2)和索引(1,2),
(8,2)和指数(0,2)、(8,1)和指数(0,3)、(4,1)以及指数(1,3)、(2,1)和指数(2,4)
用二进制索引树计算代码翻转的代码> //C++程序
#包括
使用名称空间std;
//返回arr[0..index]的和。此函数假定
//数组经过预处理,并且
//数组元素存储在BITree[]中。
int getSum(int比特树[],int索引)
{
int sum=0;//初始化结果
//遍历比特树的祖先[索引]
而(索引>0)
{
//将比特树的当前元素添加到总和
总和+=比特树[索引];
//在getSum视图中将索引移动到父节点
指数-=指数和(-index);
}
回报金额;
}
//在给定索引处更新二叉索引树(BITree)中的节点
//在比特里。将给定值“val”添加到BITree[i]中,然后
//它所有的祖先都在树上。
void updateBIT(int-BITree[],int-n,int-index,int-val)
{
//遍历所有祖先并添加“val”
while(index)在本文中,什么是“反转对”?给你一个数组A[],由N个元素组成。数组的反转计数定义为(i,j)对的数量,使得i A[j]
// C++ program to count inversions using Binary Indexed Tree
#include<bits/stdc++.h>
using namespace std;
// Returns sum of arr[0..index]. This function assumes
// that the array is preprocessed and partial sums of
// array elements are stored in BITree[].
int getSum(int BITree[], int index)
{
int sum = 0; // Initialize result
// Traverse ancestors of BITree[index]
while (index > 0)
{
// Add current element of BITree to sum
sum += BITree[index];
// Move index to parent node in getSum View
index -= index & (-index);
}
return sum;
}
// Updates a node in Binary Index Tree (BITree) at given index
// in BITree. The given value 'val' is added to BITree[i] and
// all of its ancestors in tree.
void updateBIT(int BITree[], int n, int index, int val)
{
// Traverse all ancestors and add 'val'
while (index <= n)
{
// Add 'val' to current node of BI Tree
BITree[index] += val;
// Update index to that of parent in update View
index += index & (-index);
}
}
// Returns inversion count arr[0..n-1]
int getInvCount(int arr[], int n)
{
int invcount = 0; // Initialize result
// Find maximum element in arr[]
int maxElement = 0;
for (int i=0; i<n; i++)
if (maxElement < arr[i])
maxElement = arr[i];
// Create a BIT with size equal to maxElement+1 (Extra
// one is used so that elements can be directly be
// used as index)
int BIT[maxElement+1];
for (int i=1; i<=maxElement; i++)
BIT[i] = 0;
// Traverse all elements from right.
for (int i=n-1; i>=0; i--)
{
// Get count of elements smaller than arr[i]
invcount += getSum(BIT, arr[i]-1);
// Add current element to BIT
updateBIT(BIT, maxElement, arr[i], 1);
}
return invcount;
}
// Driver program
int main()
{
int arr[] = {8, 4, 2, 1};
int n = sizeof(arr)/sizeof(int);
cout << "Number of inversions are : " << getInvCount(arr,n);
return 0;
}