Under construction

Still being built. Things may change

Fox's Dream

Time limit2sMemory limit1024 MB

Summary
Given N disks that all start on peg K, find the minimum number of moves to reach the target peg for each disk, modulo 1000000007.
Level

Medium6 of 10

Topics
Recursion, Math
Solved
No attempts yet

Problem

The legend of Fox Village says that a wish comes true when all disks of a Tower of Hanoi with 3 pegs and NN disks are gathered on one peg.

Disks move under these rules:

  • The radius of the ii-th disk is ii. (1≤i≤N1 \le i \le N)
  • At all times, the disks on one peg must be ordered so that smaller radii are on top.
  • Only the top disk on each peg can be moved.
  • A disk can only be placed on top of a peg.
  • Only one disk can be moved at a time.

A baby fox in the village heard this legend and decided to try the Tower of Hanoi. The baby fox gathered all the disks on the KK-th peg and made a wish.

"Let me become the cutest fox in the world!"

Nothing changed for the baby fox.

Disappointed, the baby fox decided to arrange the disks into a shape it finds beautiful. Now a Tower of Hanoi master, the baby fox can move one disk per second. Find the minimum time, in seconds, that the baby fox needs to arrange the disks into the beautiful shape.

Input

The first line contains NN and KK, separated by a space. (1≤N≤10000001 \le N \le 1000000; 1≤K≤31 \le K \le 3)

The second line contains NN integers separated by spaces. The ii-th number aia_i is the peg on which the ii-th disk sits in the beautiful shape. (1≤ai≤31 \le a_i \le 3)

The beautiful shape the baby fox imagined satisfies the rules of the Tower of Hanoi.

Output

Print, on the first line, the minimum time in seconds for the baby fox to build the beautiful shape, modulo 109+710^{9} + 7. 109+710^{9} + 7 is a prime.

If the beautiful shape cannot be built, print -1.

Hint

Is the legend of Fox Village true?

Examples3

  1. Example 1

    Input
    3 3
    2 3 2
    
    Expected output
    6
    
  2. Example 2

    Input
    9 2
    3 1 1 2 2 3 2 2 2
    
    Expected output
    57
    
  3. Example 3

    Input
    1 1
    1
    
    Expected output
    0