Header Ad

HackerEarth Inversions Revisited problem solution

In this HackerEarth Inversions Revisited problem solution, Most of us know how to count the number of inversions in an array. An inversion in an array is a pair of indices(i,j) such that a[i]>a[j] and i < j.

In this problem you are given 2 arrays A and B and you have to return number of such pairs such that a[i]>b[j] and i < j.


HackerEarth Inversions Revisited problem solution


HackerEarth Inversions Revisited problem solution.

#include <bits/stdc++.h>
#define _ ios_base::sync_with_stdio(false);cin.tie(0);
using namespace std;
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define mp make_pair
#define all(a) a.begin(),a.end()
#define bitcnt(x) __builtin_popcountll(x)
#define MOD 1000000007
#define total 5000005
#define M 1000000000001
#define NIL 0
#define MAXN 100001
#define EPS 1e-5
#define INF (1<<28)
typedef unsigned long long int uint64;
typedef long long int int64;

int BIT[1000006];
int a[1000006];
int b[1000006];
void upd(int idx,int val){
for(int i=idx;i<=1000000;i+=(i&(-i)))
BIT[i]+=val;
}
int query(int val){
int ret=0;
while(val){
ret+=BIT[val];
val-=(val&(-val));
}
return ret;
}
int main(){
int n,i;
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
cin>>n;
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
scanf("%d",&b[i]);
for(i=1;i<=n;i++){
upd(b[i],1);
}
int64 ans=0;
for(i=1;i<=n;i++){
upd(b[i],-1);
ans+=(query(a[i]-1));
}
cout<<ans;
fclose(stdout);
}

Second solution

#include <bits/stdc++.h>

using namespace std;

long long tree[200005];
int A[200005];
int B[200005];

long long query(int idx)
{
long long res = 0;
while ( idx > 0 ) {
res += tree[idx];
idx -= (idx & (-idx));
}
return res;
}

void update(int idx)
{
while ( idx <= 100001 ) {
tree[idx] += 1;
idx += (idx &(-idx));
}
return;
}
int main()
{
int t=1,n;
while ( t-- ){
cin >> n;
for ( int i = 0; i < n; i++ ) cin >> A[i];
for ( int i = 0; i < n; i++ ) cin >> B[i];
memset(tree, 0, sizeof(tree));
long long ans = 0;
for ( int i = n-1; i >= 0; i-- ) {
ans += query(A[i]-1);
update(B[i]);
}
cout << ans << endl;
}

return 0;
}


Post a Comment

0 Comments