Can anyone tell me how to solve this Problem using matrix, DP solution for this problem is too slow O(n*m*m) (n<=10^15). There exists a solution of O(m*m*m*logn) using matrix exponentiation. Can anyone please explain in detail how to solve this problem using matrix exponentiation!!!
We can build a graph, when edge (u, v) exists, only if pair (u, v) is not forbidden. Then we need to calculate a number of paths length of N from U to V for all (U, V) from 1 to M.
This problem we can solve using matrix exponentiation. We take the adjacency matrix and raise it to the power N — 1 (using binpow, of course) , then take sum of all elements in matrix. This will be the answer to the problem. You can see my code in submissions.
i didnt get u completely, how to create that adjacency matrix
We have a matrix A of size M x M. A[i][j] = 1, only if the pair of symbols (i, j) is not forbidden from the input.
Sample :
Here we have forbidden pairs (a , b) and (b, a) and M is 3 so we have such matrix :
Where A[i][j] = 0 for (a, b) and (b, a). 'a' is the first row in matrix, 'b' second, and 'c' third. So, that is how it looks.
You build adjacency matrix , where if and only if pair is not forbidden, so you just assign . And then for each string in the input you assign , where is a mapping function .
why raising the adjacency matrix to power N gives us the number of paths?
For N = 1 answer is obvious — it's a adjacency matrix. Let's guess, that we have answer for some k, ans now we will calc answer for k + 1. We have such obvious formula :
We can notice, that this formula is matrix multiplication :
We can raise adjacency matrix g to power of N and get the answer. I don't know TeX, sorry.
Thanks.
i didnt get this line- d1[i][j] = d1[i][j] + d[i][p] * g[p][j], for all p from 1 to M.
pls explain this.....
We need a path with length K + 1, we have a path length of K, so we need one single edge to complete path.
To completely solve the problem, we need raise to the power of N — 1 the adjacency matrix and get sum of all elements in it.
Sorry for my bad endlish)
excellent explanation and your english is not so bad. But one last question, i heard the name of binpow() first time. Can u give me some link from where i can read about this function like whats its return type etc..... :)
link