Description
Tired of the Tri Tiling game finally, Michael turns to a more challengeable game, Quad Tiling:
In how many ways can you tile a 4 × N (1 ≤ N ≤ 109) rectangle with 2 × 1 dominoes? For the answer would be very big, output the answer modulo M (0 < M ≤ 105).
Input
Input consists of several test cases followed by a line containing double 0. Each test case consists of two integers, N and M, respectively.
Output
For each test case, output the answer modules M.
Sample Input
1 10000 3 10000 5 10000 0 0
Sample Output
1 11 95
Source
这题和上一题差不多,不过要用矩阵乘法,很显然16*16,照例先预处理所有每一行可以放的情况(横着放的用1,竖着放的用0),之后再算出每种状态互相有几种转移方式,最后矩阵乘法水过。
有个trick 当n=1,m=1的时候直接输出0、
over,上代码
另外,和上一题一样,我在此强调,那个预处理的数组原来我要用单词available的,但是因为单词太长了,所以我只取前两个字母,木有别的意思!!真的木有!!!
#include <stdio.h> #include <string.h> typedef struct { int ma[20][20]; }Matrix; Matrix a,b,c; int av[20]; int vis[20]; int m; Matrix Mul(Matrix p,Matrix q) { int i,j,k; for (i=0;i<16;i++) { for (j=0;j<16;j++) { c.ma[i][j]=0; for (k=0;k<16;k++) { c.ma[i][j]=(c.ma[i][j]+p.ma[i][k]*q.ma[k][j])%m; } } } return c; } int main() { int i,j,n,up,t,k; while(1) { scanf("%d%d",&n,&m); up=0; if (n==0 && m==0) break; if (m==1) { printf("0\n"); continue; } for (i=0;i<(1<<4);i++) { memset(vis,0,sizeof(vis)); for (j=1;j<4;j++) { if (vis[j-1]==false && ((i & (1<<(j-1)))!=0) && ((i & (1<<(j)))!=0)) { vis[j-1]=vis[j]=1; } } for (j=0;j<4;j++) { if (vis[j]==0 && ((i & (1<<(j)))!=0)) break; } if (j==4) av[up++]=i; } // for (i=0;i<up;i++) printf("%d...%d\n",av[i],up); memset(a.ma,0,sizeof(a.ma)); for (i=0;i<(1<<4);i++) { for (j=0;j<up;j++) { t=0; for (k=3;k>=0;k--) { if ((i & (1<<k))==(av[j] & (1<<k))) t=t*2+1; else if ((i & (1<<k))!=0) t=t*2; else break; } if (k==-1) a.ma[i][t]++; } } memset(b.ma,0,sizeof(b.ma)); for (i=0;i<up;i++) { b.ma[av[i]][0]=1; } n--; while(n!=0) { if (n & 1) { b=Mul(a,b); } n>>=1; a=Mul(a,a); } printf("%d\n",b.ma[15][0]); } return 0; }