Nyoj 302 星际旅行[矩阵乘法求两点k步方案数]

来源:互联网 发布:21天学通java第7版pdf 编辑:程序博客网 时间:2024/04/30 06:35

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=302

题目意思。。n*m的矩阵。。每个元素代表一个星球,每个元素的值为所属国家,也就是每个星球属于一个国家。。每个相邻(上下左右)的星球有一个航道。每个国家的任意的两个星球都有星际之门。。。。。问,从(1,1)星球到(n,m)星球的方案数。。。相同的方案为走过的星球顺序相同。。。。。

处理一下图就是很裸的问题。。。

处理图的方式有很多中。。。

我的方法为,把二维矩阵散列到一维上。。然后,两两判断是否有通路。。然后处理到邻接矩阵中。。。。直接矩阵乘法就好。。。

Code:

 #include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <cmath>using namespace std;#define LL long longconst int N = 105;const LL mod = 1000007;struct Matrix{    int n;    LL a[N][N];    Matrix(){        memset(a, 0, sizeof(a));    }} ans, A;int node[N], n;int m, p;bool Judge(int x, int y){    if(x - n == y) return true;    else if(x + n == y) return true;    else if(x - 1 == y && y % n != 0) return true;    else if(x + 1 == y && x % n != 0) return true;    else return false;}Matrix operator * (Matrix a, Matrix b){    Matrix tmpans;    tmpans.n = a.n;    for(int i = 1; i <= a.n; i ++){        for(int j = 1; j <= a.n; j ++){            for(int k = 1; k <= a.n; k ++)            tmpans.a[i][j] = (tmpans.a[i][j] + a.a[i][k] * b.a[k][j]) % mod;//            printf("k = %d\n", tmpans.a[i][j]);        }    }    return tmpans;}void power(int k){    while(k){        if(k & 1) ans = ans * A;        A = A * A;        k = k >> 1;    }}int main(){//    freopen("1.txt", "r", stdin);    int T;    cin >> T;    while(T --){        cin >> n >> m >> p;        for(int i = 0; i < m; i ++){            for(int j = 1; j <= n; j ++){                cin >> node[i * n + j];            }        }        for(int i = 1; i <= m * n; i ++){            for(int j = 1; j <= m * n; j ++){                A.a[i][j] = 0; ans.a[i][j] = 0;                if(i == j) continue;                if(node[i] == node[j]) A.a[i][j] = 1;                else if(Judge(i, j)){                    A.a[i][j] = 1;                }            }            ans.a[i][i] = 1;        }        ans.n = n * m; A.n = n * m;        power(p);        printf("%lld\n", ans.a[1][n * m] % mod);    }    return 0;}        

表示NYOJ上关于矩阵的题目数据的还是很强大的。。。。

0 0
原创粉丝点击