Ant
Time limit1sMemory limit128 MB
Count walks of exactly k edges from one cube vertex to another, never reusing the edge just used, modulo p.
- Level
Medium7 of 10
- Topics
- Matrix, Dynamic programming, Math, Combinatorics
- Solved
- No attempts yet
Problem
An ant walks along the edges of a cube .

The ant wants to find out in how many ways it can travel from one given vertex to another given vertex by crossing exactly edges. (Once the ant steps onto an edge it never turns back partway, and always walks all the way to the other end of that edge.) If the ant crosses some edge times, that edge is counted times.
The ant only wants to count interesting routes: whenever it arrives at a vertex, it wants to leave that vertex through an edge different from the one it just used to enter it (it never uses the same edge twice in a row).
The ant can only count integers from to for some , so report the answer modulo .
The cube is structured as follows: the bottom face is the square (edges , , , ), the top face is the square (edges , , , ), and the vertical edges , , , connect the two faces (12 edges in total).
Write a program that:
- reads the starting vertex, the ending vertex, the number of edges on the route, and the integer ,
- computes the number of interesting routes that satisfy the conditions above, modulo ,
- writes the answer to standard output.
Input
The first line contains two uppercase English letters and (, ), separated by a single space, denoting the starting and the ending vertex respectively. The second line contains two integers and (, ), separated by a single space.
Output
Output a single integer: the number of interesting routes from vertex to vertex using exactly edges, modulo .
Hint
