Python Program to find out the determinant of a given special matrix


Suppose, we have a tree with n vertices, where each vertex is labeled from 1 to n. The root of the tree has the label 1, and each vertex weights wi. Now a nxn matrix A is formed where A(x,y) = Wf(x, y) where f(x, y) is the least common predecessor of vertex x and y. We have to find out the determinant of matrix A. The edges of the matrix, weights, and the total number of vertices are given to us as input.

So, if the input is like input_array = [[1, 2], [1, 3], [1, 4], [1, 5]], weights = [1, 2, 3, 4, 5], vertices = 5, then the output will be 24.

The matrix A is given as =

11111
12111
11311
11141
11115

the determinant of this matrix is 24.

To solve this, we will follow these steps −

  • w := an empty list
  • for i in range 0 to vertices, do
    • add weights[i] and a new list to w
  • for each i, item in enumerate(input_array), do
    • p := item[0]
    • q := item[1]
    • insert q - 1 at the end of w[p - 1, 1]
    • insert p - 1 at the end of w[q - 1, 1]
  • det := 1
  • stack := a stack containing a tuple (0, 0)
  • while stack is not empty, do
    • i, weights := delete top element from stack
    • det := (det * (w[i, 0] - weights)) mod (10^9 + 7)
    • for t in w[i][1], do
      • add tuple containing (t,w[i,0]) to the stack
      • for each t in w[i][1], do
        • delete i from w[t,1]
  • return det

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(input_array, weights, vertices):
   w = [[weights[i],[]] for i in range(vertices)]
   for i, item in enumerate(input_array):
      p,q = item[0], item[1]
      w[p - 1][1].append(q - 1)
      w[q - 1][1].append(p - 1)
   det = 1
   stack = [(0,0)]
   while stack:
      i, weights = stack.pop()
      det = (det * (w[i][0] - weights)) % (10**9 + 7)
      stack += [(t,w[i][0]) for t in w[i][1]]
      for t in w[i][1]:
         w[t][1].remove(i)
   return det
print(solve([[1, 2], [1, 3], [1, 4], [1, 5]], [1, 2, 3, 4, 5], 5))

Input

[[1, 2], [1, 3], [1, 4], [1, 5]], [1, 2, 3, 4, 5], 5

Output

24

Updated on: 18-May-2021

353 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements