poj 3420

Quad TilingTime Limit: 1000MS Memory Limit: 65536K
Total Submissions: 2265 Accepted: 915


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
POJ Monthly--2007.10.06, Dagger

分析:直接套公式了,不会推导耶。。。

代码:

#include<cstdio> int i,j,k,n,m; __int64 a[4][4],b[4][4],c[4][4],s[4]={1,5,11,36},o[4][4]={{0,0,0,-1},{1,0,0,1},{0,1,0,5},{0,0,1,1}},ans; void cal(__int64 a[4][4],__int64 b[4][4]) { for(i=0;i<4;++i) for(j=0;j<4;++j)c[i][j]=0; for(i=0;i<4;++i) for(k=0;k<4;++k) if(a[i][k])for(j=0;j<4;++j)c[i][j]+=a[i][k]*b[k][j]; for(i=0;i<4;++i) for(j=0;j<4;++j)a[i][j]=c[i][j]%m; } int main() { while(scanf("%d%d",&n,&m),n) { for(i=0;i<4;++i) for(j=0;j<4;++j)a[i][j]=o[i][j],b[i][j]=i==j; if(--n>3) { n-=3; while(n>0) { if(n&1)cal(b,a); cal(a,a); n>>=1; } for(ans=i=0;i<4;++i)ans+=s[i]*b[i][3]; } else ans=s[n]; if((ans%=m)<0)ans=(ans+m)%m; printf("%I64d/n",ans); } }

你可能感兴趣的:(c,input,each,output)