Computer Science, asked by prakharpuri1999, 9 months ago

Monk and Inversions Monk's best friend Micro, who happen to be an awesome programmer, got him an integer matrix M of size for his birthday. Monk is taking coding classes from Micro. They have just completed array inversions and Monk was successful in writing a program to count the number of inversions in an array. Now, Micro has asked Monk to find out the number of inversion in the matrix M. Number of inversions, in a matrix is defined as the number of unordered pairs of cells such that . Monk is facing a little trouble with this task and since you did not got him any birthday gift, you need to help him with this task. Input: First line consists of a single integer T denoting the number of test cases. First line of each test case consists of one integer denoting N. Following N lines consists of N space separated integers denoting the matrix M. Output: Print the answer to each test case in a new line.

Answers

Answered by prachisharma3206
6

Answer:

This is a programming question that I had when I was interviewed by a company for a developer job few months ago.

Given an array A of N integers, an inversion of the array is defined as any pair of indexes (a,b) such that a<b and A[b]<A[a].

Write a function:

int inversion_count(int A[], int n);

which computes the number of inversions in A, or returns -1 if such number exceeds 1,000,000,000. For example, in the following array

A[0]=-1 A[1]=6 A[2]=3 A[3]=4 A[4]=7 A[5]=4

there are four inversions:

(1,2) (1,3) (1,5) (4,5)

so the function should return 4.

I solved this question in a very common way: using double loop.

int i, j;

long count;

for (i = 0; i < n; i++) {

for (j = i+1; j < n; j++) {

if (A[i] > A [j]) count++;

if (count > 1000000000) break; // exit loop

}

if (count > 1000000000) break; // exit loop

}

if (count > 1000000000) return -1;

else return count;

So the running time of it is : O (nsquare), and I was told that it was not efficient. I am now thinking of a different way to solve this problem, maybe using an n log n algorithm, but I haven't figured it out yet. Any ideas?

Answered by syed2020ashaels
0

In the question it is said that Monk was successful in writing a program to count the number of inversions in an array.

we have to write a program according to the instructions given in the question.

let us write a program according to the question.

int inversion_count (int P[], int n) ; it returns -1 if such no exceeds 1000000000

P[0]=-1

P[1]=6

P[2]=3 there will be 4 inversions.

P[3]=4

P[4]=7

P[5]=4

(1, 2) (1, 3) (1, 4) (4, 5) it should return 4.

double loop is used to slove this question.

int I, j;

long count;

for (i=0;I<n;I++) {

for(j=I+1;j<n;j++) {

if (P[i]>P[j]) count++;

if(count > 1000000000)

break;

exit

loop

}

if (count >1000000000)

break;

exit loop

}

if(count > 1000000000)

return -1;

else return count;

the running time will be 0.

# spj2

Similar questions