Paths of length K
InterviewTime limit2sMemory limit512 MB
Count the number of length-K walks in a directed graph given its adjacency matrix, where K can be as large as 10^9, and output the count modulo 10^9+7.
- Level
Medium6 of 10
- Topics
- Matrix, Graph, Divide and conquer, Math
- Solved
- No attempts yet
Problem
The country of Cheon has villages, numbered 1 to . Between two villages there may or may not be a road, and every road has length 1. A road can be traveled in one direction only.
Minho wrote the connections between the villages into an adjacency matrix. If the -th number on line is 1, there is a road from village to village ; if it is 0, that road does not exist. A 1 on the diagonal means the village has a road back to itself.
A path of length is a sequence of village numbers such that for every there is a road from village to village . A path may pass through the same village several times, and and are unrestricted. Two paths count as different if their sequences differ in at least one position.
Given the adjacency matrix, count the different paths of length .
Input
The first line contains and , separated by one space. (, )
Each of the next lines contains integers, each either 0 or 1, separated by spaces. Together they form the adjacency matrix.
Output
Print the number of paths of length modulo on one line.
Hint
In the first example the six paths of length 2 are:
- 1 → 2 → 3
- 1 → 3 → 4
- 2 → 3 → 4
- 3 → 4 → 1
- 4 → 1 → 2
- 4 → 1 → 3