Count Inversions
JavaScript
Hard
6 views
Problem Description
Count number of inversions in the array (iarr[j]). Print the count.
Input Format
One line: n then n integers.
Output Format
One integer count.
Official Solution
const fs=require('fs');const p=fs.readFileSync(0,'utf8').trim().split(/\\s+/);if(!p[0])process.exit(0);let i=0;const n=Number(p[i++]);let arr=new Array(n);for(let j=0;j<n;j++)arr[j]=Number(p[i++]);let vals=[...arr].sort((a,b)=>a-b);vals=[...new Set(vals)];const idxMap=new Map();for(let j=0;j<vals.length;j++)idxMap.set(vals[j],j+1);const bit=new Array(vals.length+2).fill(0);const add=(x,v)=>{for(;x<bit.length;x+=x&-x)bit[x]+=v;};const sum=x=>{let s=0;for(;x>0;x-=x&-x)s+=bit[x];return s;};let inv=0n;for(let j=n-1;j>=0;j--){const id=idxMap.get(arr[j]);inv+=BigInt(sum(id-1));add(id,1);}process.stdout.write(inv.toString());
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!