`
java-mans
  • 浏览: 11411341 次
文章分类
社区版块
存档分类
最新评论

POJ 3734 Blocks 矩阵乘法

 
阅读更多

依旧是神奇的矩阵乘法,构思很巧妙,虽说看着很简单,但是确实没练过矩阵题,所以就没这个意识去想到状态转移矩阵了。

依旧是参考的别人的思路,也坚定了我要学好矩阵的决心。

有四种颜色,其中红色和绿色必须是偶数,那么我们可以分四种状态,

一,红为偶数,绿为偶数

二,红为奇数,绿为偶数,

三,红为偶数,绿为奇数

四,红为奇数,绿为奇数

那么我们构造一个矩阵

2 1 1 0
1 2 0 1
1 0 2 1
0 1 1 2
每一行分别对应一种状态

以第一行为例子,从n-1个块转成n个块时

1,1 由于第一种状态可以由(n-1)块砖为第一种状态时加蓝或黄转化,所以有2种情况

1,2 由于第一种状态可以由(n-1)块砖第二种状态时加红转化,所以只有1种

1,3 由于第一种状态可以有(n-1)块砖第三种状态时加绿转化,所以这里也是1种

1,4 由于第一种状态无法有(n-1)块砖第四种状态时转化而来,所以这里是0


然后就是矩阵连乘,快速幂了

/*
ID: sdj22251
PROG: subset
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define LOCA
#define MAXN 500005
#define INF 100000000
#define eps 1e-7
#define L(x) x<<1
#define R(x) x<<1|1
using namespace std;
int n = 4, m;
int tt[4][4]={2,1,1,0,1,2,0,1,1,0,2,1,0,1,1,2};
struct wwj
{
    int r, c;
    int mat[5][5];
} need, pea;
void init()
{
    memset(need.mat, 0, sizeof(need.mat));
    need.r = n;
    need.c = n;
    for(int i = 1; i <= n; i++)
    {
        need.mat[i][i] = 1;
    }
    pea.c = n;
    pea.r = n;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        pea.mat[i][j] = tt[i - 1][j - 1];
    }
}
wwj multi(wwj x, wwj y)
{
    wwj t;
    int i, j, k;
    memset(t.mat, 0, sizeof(t.mat));
    t.r = x.r;
    t.c = y.c;
    for(i = 1; i <= x.r; i++)
    {
        for(k = 1; k <= x.c; k++)
            if(x.mat[i][k])
            {
                for(j = 1; j <= y.c; j++)
                {
                    t.mat[i][j] += (x.mat[i][k] * y.mat[k][j]) % 10007;
                    t.mat[i][j] %= 10007;
                }
            }
    }
    return t;
}
int main()
{
#ifdef LOCAL
    freopen("d:/data.in","r",stdin);
    freopen("d:/data.out","w",stdout);
#endif
    int i, j, p, x, y, k, t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &m);
        init();
        while(m)
        {
            if(m & 1)
            {
                need = multi(pea, need);
            }
            pea = multi(pea, pea);
            m = m >> 1;
        }
        printf("%d\n", need.mat[1][1] % 10007);
    }
    return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics