Counting Cycles
Time limit2sMemory limit512 MB
Count all closed walks (cycles) of length less than K in a directed graph, where rotations count separately, modulo M.
- Level
Hard8 of 10
- Topics
- Graph, Matrix, Dynamic programming, Combinatorics
- Solved
- No attempts yet
Problem
You are given a directed graph . Write a program that counts the distinct cycles of length less than . The count can be very large, so print it modulo .
A cycle is a sequence of nodes, and the same node may appear more than once. There must be an edge from each node to the next node, and there must also be an edge from the last node to the first node. The length of a cycle is the number of nodes in the sequence. Two sequences in a different order count as different cycles. For example, and are different cycles.
The nodes are numbered from to .
Input
The first line contains the number of nodes of the graph , followed by and . (, , )
Each of the next lines gives the edges of the graph as an adjacency matrix. The -th character of the -th line describes the edge from node to node . Y means the edge exists and N means it does not. The graph has no loops, so the -th character of the -th line is always N.
Output
Print the number of distinct cycles of length less than , modulo , on the first line.
Hint
In the first example, the cycles of length less than are the following.
- , , , , , , , , , , ,