Watan and Dominoes

Pre-requisite :

Segment tree or fenwick tree

Problem statement :

Given an array, you have to print for each position, how many elements appearing before it
are smaller than it.

Explanation: The problem is a standard problem known as finding the number of inversions in an array. If we apply a bruteforce and count how many elements appearing before an element are smaller, this will time out (O(n^2)).

We need a better approach. We can create a hash table where each positon will have 0
initially. For each element Ai, we can increment the value of hash[Ai] by 1. Since it is a hash table, if an element ‘x’ smaller than Ai appering before Ai is there, then hash[x] won’t be 0 and hash[x] will appear before hash[Ai]. So finding the sum of values from hash[1] to hash[Ai - 1] will be equal to number of elements smaller than Ai appearing before Ai.

Consider this example.

A = {1, 3, 5};

hash[] = {0, 0, 0, 0, 0, 0}

when we visit 1, hash[1] = 1

hash[] = {0, 1, 0, 0, 0, 0}

Sum of all values before 1 , i.e. hash[0] = 0, so elements smaller than 1 appearing before 1 is 0

when we visit 3, hash[3] = 1

Sum of all values before 3 , i.e. hash[0] + hash[1] + hash[2] = 1, so elements smaller than 3

appearing before 3 is 1

Now this approach is slow considering we have to find the sum of elements in linear time for each entry. We can make it logarithmic by using a segment tree or a fenwick tree. Both returns sum from first to Aith element in logarithmic time. Also we increment value in hash table in logarithmic time.

See the solution code which uses a fenwick tree.

### Solution:

#include
#include
#define MAX 1000009
int tree[MAX];
void init()
{
	memset(tree,0,sizeof(tree));
}
void add(int index)
{
	while(index 0)
	{
		s+=tree[index];
		index = index - (index & -index);
	}
	return s;
}
int main()
{
	int test;
	scanf("%d",&test);
	while(test--)
	{
		init();
		int n,input;
		scanf("%d",&n);
		while(n--)
		{
			scanf("%d",&input);
			
			add(input);
			printf("%d ",sum(input-1));
			
		}
		printf("\n");
	}
	return 0;
}
//