samedi 11 avril 2020

Count the no of shifts in insertion sort using Fenwick tree (Binary index tree) in C++

I was attempting to solve the hackerrank problem on insertion sort that asks to calculate the number of shifts while sorting the array using insertion sort - https://www.hackerrank.com/challenges/insertion-sort/leaderboard. Seeing on the disccussion forums I get to know that using concept of binary index tree , the solution can be optimized for this question. I even understood the concept of BIT using link - https://www.hackerearth.com/practice/notes/binary-indexed-tree-or-fenwick-tree/. But still I was not able to understand how it applies in this question. I may be sounding dumb , but any intutive explanation along with the below code that I found on the forum that uses BIT concept, but some more lucid explanation will help me a lot to actually grasp the solution.

/* Enter your code here. Read input from STDIN. Print output to STDOUT */
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std ;
#define MAXN 100002
#define MAX 1000002
int n,a[MAXN],c[MAX] ;
int main()
{
 int runs ;
 scanf("%d",&runs) ;
 while(runs--)
 {
  scanf("%d",&n) ;
  for(int i = 0;i < n;i++) scanf("%d",&a[i]) ;
  long long ret = 1LL * n * (n - 1) / 2 ;
  memset(c,0,sizeof c) ;
  for(int i = 0;i < n;i++)
  {
   for(int j = a[i];j > 0;j -= j & -j) ret -= c[j] ;
   for(int j = a[i];j < MAX;j += j & -j) c[j]++ ;
  }
  cout << ret << endl ;
 }
 return 0 ;
}

Aucun commentaire:

Enregistrer un commentaire