• HDU 2157 How many ways?? 矩阵


    可达矩阵的K次幂便是从i到j走K步能到达的方案数。

    注意处理k=0的情况。

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <queue>
    #include <stack>
    #include <map>
    #include <set>
    #include <climits>
    #include <iostream>
    #include <string>
    
    using namespace std;
     
    #define MP make_pair
    #define PB push_back
    typedef long long LL;
    typedef unsigned long long ULL;
    typedef vector<int> VI;
    typedef pair<int, int> PII;
    typedef pair<double, double> PDD;
    const int INF = INT_MAX / 3;
    const double eps = 1e-8;
    const LL LINF = 1e17;
    const double DINF = 1e60;
    const int maxn = 30;
    const int mod = 1000;
    
    struct Matrix {
        int n, m, data[maxn][maxn];
        Matrix(int n = 0, int m = 0): n(n), m(m) {
            memset(data, 0, sizeof(data));
        }
    };
    
    Matrix operator * (Matrix a, Matrix b) {
        Matrix ret(a.n, b.m);
        for(int i = 1; i <= a.n; i++) {
            for(int j = 1; j <= b.m; j++) {
                for(int k = 1; k <= a.m; k++) {
                    ret.data[i][j] += a.data[i][k] * b.data[k][j];
                    ret.data[i][j] %= mod;
                }
            }
        }
        return ret;
    }
    
    Matrix pow(Matrix mat, int p) {
        if(p == 0) {
            Matrix ret(mat.n, mat.m);
            for(int i = 1; i <= mat.n; i++)  ret.data[i][i] = 1;
            return ret;
        }
        if(p == 1) return mat;
        Matrix ret = pow(mat * mat, p / 2);
        if(p & 1) ret = ret * mat;
        return ret;
    }
    
    int n, m;
    
    int main() {
        while(scanf("%d%d", &n, &m), n) {
            Matrix mat(n, n);
            for(int i = 1; i <= m; i++) {
                int a, b; scanf("%d%d", &a, &b);
                mat.data[a + 1][b + 1] = 1;
            }
            int Q; scanf("%d", &Q);
            while(Q--) {
                int a, b, k; scanf("%d%d%d", &a, &b, &k);
                Matrix ret = pow(mat, k);
                printf("%d
    ", ret.data[a + 1][b + 1]);
            }
        }
        return 0;
    }
    

      

  • 相关阅读:
    [BZOJ1620][Usaco2008 Nov]Time Management 时间管理
    [BZOJ1634][Usaco2007 Jan]Protecting the Flowers 护花
    [BZOJ1725][Usaco2006 Nov]Corn Fields牧场的安排
    [BZOJ1708][Usaco2007 Oct]Money奶牛的硬币
    [BZOJ1690][Usaco2007 Dec]奶牛的旅行
    fzu 2132 LQX的作业
    fzu 2139 久违的月赛之二
    poj 1849 Two 树形dp
    师范大学 e: skyscrapers
    O(∩_∩)O~~
  • 原文地址:https://www.cnblogs.com/rolight/p/4049001.html
Copyright © 2020-2023  润新知