hdu 2563 统计问题

题目:统计问题

思路:将问题转换成,前一状态是左或者右的,或者前的,设左右的那种是A(n-1),前的那种是B(n-1),那么对于当前的状态,如果现在往前B(n)=2*A(n-1)+B(n-1),如果往左:A(n)=A(n-1)+B(n-1) 往右的相同,那么对于这样的一个问题,可以构造矩阵或者求递推式,练下矩阵,所以写成构造矩阵的了

 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
struct Matrix
{
    int m[3][3];
}E,D;
void init()
{
    for(int i=1;i<=2;i++)
        for(int j=1;j<=2;j++)
        {
            E.m[i][j]=(i==j);
            D.m[i][j]=1;
        }
    D.m[2][1]=2;
}
Matrix Multi(Matrix A,Matrix B)
{
    Matrix ans;
    for(int i=1;i<=2;i++)
        for(int j=1;j<=2;j++)
        {
            ans.m[i][j]=0;
            for(int k=1;k<=2;k++)
                ans.m[i][j]+=A.m[i][k]*B.m[k][j];
        }
    return ans;
}
Matrix Pow(Matrix A,int k)
{
    Matrix ans=E;
    while(k)
    {
        if(k&1)
        {
            k--;
            ans=Multi(ans,A);
        }
        else
        {
            k/=2;
            A=Multi(A,A);
        }
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    init();
    while(t--)
    {
        int n;
        scanf("%d",&n);
        Matrix ans=Pow(D,n);
        printf("%d\n",ans.m[1][1]+ans.m[2][1]);
    }
    return 0;
}
View Code

 

posted @ 2013-06-20 10:34  over_flow  阅读(143)  评论(0编辑  收藏  举报