poj #3734 Blocks(矩阵快速幂)

来源:互联网 发布:手机上c语言编程软件 编辑:程序博客网 时间:2024/06/04 23:34

这题也是属于“dp优化”的一类。本题解法有矩阵快速幂和组合数学两种(后者写起来会简单很多,但是推导过程繁琐),所以选用了矩阵快速幂的方法。
标签:矩阵快速幂
Blocks

Time Limit: 1000MS Memory Limit: 65536K
Description

Panda has received an assignment of painting a line of blocks. Since Panda is such an intelligent boy, he starts to think of a math problem of painting. Suppose there are N blocks in a line and each block can be paint red, blue, green or yellow. For some myterious reasons, Panda want both the number of red blocks and green blocks to be even numbers. Under such conditions, Panda wants to know the number of different ways to paint these blocks.

Input

The first line of the input contains an integer T (1≤ T ≤100), the number of test cases. Each of the next T lines contains an integer N (1≤ N ≤10^9) indicating the number of blocks.

Output

For each test cases, output the number of ways to paint the blocks in a single line. Since the answer may be quite large, you have to module it by 10007.


题意大概就是有红、黄、蓝、绿四种块,要求红、绿两种块的数量必须为偶数,求有多少种放块的方案数。
对于这道题不难想到用dp的方法,如果我们令
f[i][1] 表示前i个块,红、绿色块均为偶数个的方案数
f[i][2] 表示前i个块,红色块为偶数个、绿色块为奇数个的方案数
f[i][3] 表示前i个块,红色块为奇数个、绿色块为偶数个的方案数
f[i][4] 表示前i个块,红、绿色块均为奇数个的方案数
那么对于n>=2,转移方程为
f[i][1]=f[i1][1]2+f[i1][2]1+f[i1][3]1+f[i1][4]0
f[i][2]=f[i1][1]1+f[i1][2]2+f[i1][3]0+f[i1][4]1
f[i][3]=f[i1][1]1+f[i1][2]0+f[i1][3]2+f[i1][4]1
f[i][4]=f[i1][1]0+f[i1][2]1+f[i1][3]1+f[i1][4]2
(很容易推导出来)
如果我们直接用一个for循环暴力去算,时间复杂度是O(4n),对于N ≤10^9,这显然是不能接受的。
如果将其表示为矩阵,就是

2110120110210112

这时候我们可以利用矩阵快速幂去解决这道题,需要注意的一个细节问题,就是算快速幂的时候,矩阵初值要赋为单位矩阵(不懂自己问度娘),下面是代码。

#include<cstdio>#include<algorithm>#include<cstring>#define maxn 5#define ha 10007#define clear(x) x.w=x.u=0,memset(x.a,0,sizeof(x.a));using namespace std;typedef long long ll;struct matrix{    int w,u; //length,width    ll a[maxn][maxn];};matrix multi(matrix x,matrix y) //matrix multiplication {    int i,j,k;    matrix tmp; clear(tmp); tmp.w=tmp.u=4;    for (i=1;i<=4;i++)        for (j=1;j<=4;j++)        {            if (!x.a[i][j]) continue;            for (k=1;k<=4;k++)            {                tmp.a[i][k]+=x.a[i][j]*y.a[j][k];                tmp.a[i][k]%=ha;            }         }    return tmp;}matrix power(matrix s,int p) //matrix fast power {    int i;    matrix res; clear(res); res.w=res.u=4;    for (i=1;i<=4;i++) res.a[i][i]=1;    while (p)    {        if (p&1) res=multi(res,s);        p>>=1;        s=multi(s,s);    }    return res;}int main(){    int t,n;    matrix k; clear(k); k.w=k.u=4;    k.a[1][1]=2; k.a[1][2]=1; k.a[1][3]=1; k.a[1][4]=0;    k.a[2][1]=1; k.a[2][2]=2; k.a[2][3]=0; k.a[2][4]=1;    k.a[3][1]=1; k.a[3][2]=0; k.a[3][3]=2; k.a[3][4]=1;    k.a[4][1]=0; k.a[4][2]=1; k.a[4][3]=1; k.a[4][4]=2;    scanf("%d",&t);    while (t--)    {        scanf("%d",&n); matrix ans=power(k,n);        printf("%d\n",ans.a[1][1]);    }    return 0;}
0 0
原创粉丝点击