Blocks

来源:互联网 发布:sql字符串截取 编辑:程序博客网 时间:2024/04/30 15:52

题目:
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.

题意:
给N个格子分别涂上红、绿、蓝、黄四种颜色,使得红色格子和绿色格子的数量都是偶数个,问有几种涂色方式

题解:
a[i] 表示涂到第i个格子,红色和绿色格子的数量都为偶数
b[i] 表示涂到第i个格子,红色和绿色格子的数量一奇一偶
c[i] 表示涂到第i个格子,红色和绿色格子的数量都为奇数
则有
a[i] = 2 * a[i-1] + b[i];
b[i] = 2 * a[i-1] + 2 * c[i-1] + 2 * b[i-1];
c[i] = 2 * c[i-1] + b[i];
矩阵快速幂求解

代码:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>#include <time.h>#include <iostream>#include <algorithm>#include <string>#include <set>#include <map>#include <queue>#include <stack>#include <vector>using namespace std;const int mod = 10007;struct Matrix{    int n,m,d[5][5];    Matrix (int a,int b)    {        n = a, m = b;        memset(d,0,sizeof(d));    }    void Copy(int *tmp)    {        for (int i=0;i<n;i++)            for (int j=0;j<m;j++)            {                d[i][j] = (*tmp) % mod;                tmp++;            }    }    friend Matrix operator * (const Matrix &a,const Matrix &b)    {        Matrix c(a.n,b.m);        for (int i=0;i<a.n;i++)            for (int j=0;j<b.m;j++)            {                int tmp = 0;                for (int k=0;k<a.m;k++)                {                    tmp += a.d[i][k] * b.d[k][j] % mod;                    tmp %= mod;                }                c.d[i][j] = tmp % mod;            }        return c;    }};int solve(int n){    Matrix A(1,3),B(3,3);    int x[3] = {1,0,0};    int y[9] =    {        2,0,2,        0,2,2,        1,1,2    };    A.Copy(x);    B.Copy(y);    while (n)    {        if (n & 1) A = A*B;        B = B*B;        n >>= 1;    }    return A.d[0][0];}int main(){    int T,n;    scanf("%d",&T);    while (T--)    {        scanf("%d",&n);        printf("%d\n",solve(n));    }    return 0;}
原创粉丝点击