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

PythonServer Side ProgrammingProgramming

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 =

 1 1 1 1 1 1 2 1 1 1 1 1 3 1 1 1 1 1 4 1 1 1 1 1 5

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
• q := item
• 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], do
• add tuple containing (t,w[i,0]) to the stack
• for each t in w[i], 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, item
w[p - 1].append(q - 1)
w[q - 1].append(p - 1)
det = 1
stack = [(0,0)]
while stack:
i, weights = stack.pop()
det = (det * (w[i] - weights)) % (10**9 + 7)
stack += [(t,w[i]) for t in w[i]]
for t in w[i]:
w[t].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