Under construction

Still being built. Things may change

Counting Cycles

Time limit2sMemory limit512 MB

Summary
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 GG. Write a program that counts the distinct cycles of length less than KK. The count can be very large, so print it modulo MM.

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, (0,1,2)(0, 1, 2) and (1,2,0)(1, 2, 0) are different cycles.

The nodes are numbered from 00 to N−1N-1.

Input

The first line contains the number of nodes NN of the graph GG, followed by KK and MM. (1≤N≤351 \le N \le 35, 1≤K≤1061 \le K \le 10^6, 1≤M≤1091 \le M \le 10^9)

Each of the next NN lines gives the edges of the graph as an adjacency matrix. The jj-th character of the ii-th line describes the edge from node ii to node jj. Y means the edge exists and N means it does not. The graph has no loops, so the ii-th character of the ii-th line is always N.

Output

Print the number of distinct cycles of length less than KK, modulo MM, on the first line.

Hint

In the first example, the cycles of length less than 66 are the following.

  • (0,3)(0,3), (3,0)(3,0), (0,1,2)(0,1,2), (1,2,0)(1,2,0), (2,0,1)(2,0,1), (0,3,0,3)(0,3,0,3), (3,0,3,0)(3,0,3,0), (0,1,2,0,3)(0,1,2,0,3), (0,3,0,1,2)(0,3,0,1,2), (1,2,0,3,0)(1,2,0,3,0), (2,0,3,0,1)(2,0,3,0,1), (3,0,1,2,0)(3,0,1,2,0)

Examples6

  1. Example 1

    Input
    4 6 100
    NYNY
    NNYN
    YNNN
    YNNN
    
    Expected output
    12
    
  2. Example 2

    Input
    7 40 13
    NYNNNNN
    NNYNNNN
    NNNYNNN
    NNNNYNN
    NNNNNYN
    NNNNNNY
    YNNNNNN
    
    Expected output
    9
    
  3. Example 3

    Input
    4 1000000 1000000000
    NYNY
    NNNN
    YYNY
    NYNN
    
    Expected output
    0
    
  4. Example 4

    Input
    2 1500 1
    NY
    YN
    
    Expected output
    0
    
  5. Example 5

    Input
    7 30 100
    NYYNYYN
    YNYNYNY
    NYNYNYN
    YYYNYNY
    NNYYNNY
    NYYYNNY
    YYYYYYN
    Expected output
    72
    
  6. Example 6

    Input
    4 1000 10000
    NYYY
    YNYY
    YYNY
    YNYN
    
    Expected output
    3564