hdu 2157 How many ways?? 矩阵快速幂

hdu 2157 How many ways?? 矩阵快速幂

题目链接hdu 2157 How many ways?? 
分析:令M[i][j] = 1 表示从i到j 连通,即i, j经过一个点到达的方案数为1。 那么∑(M[i][k] + M[k][j]), k∈(0, N-1), 就表示i, j经过两个点到达的方案数。即将矩阵M^n就可以求出i, j经过N个点到达的方案数。
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;

//#pragma comment(linker, "/STACK:1024000000,1024000000")

#define FIN             freopen("input.txt","r",stdin)
#define FOUT            freopen("output.txt","w",stdout)

typedef __int64  LL;
// typedef long long LL;
typedef unsigned int uint;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;

const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int MAXN = 20;
const int MOD = 1000;

int T;
int K, A, B, N, M;
int s, t;
struct Mat {
    LL mat[MAXN][MAXN];
    Mat() {
        memset(mat, 0, sizeof(mat));
    }
    Mat(LL arr[][MAXN]) {
        Mat();
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                mat[i][j] = arr[i][j];
            }
        }
    }
} E, tmat, imat, res;
void init() {
    E = Mat();
    for (int i = 0; i < N; i++) {
        E.mat[i][i] = 1;
    }
}
Mat mat_mul(const Mat& a, const Mat& b, const int& MOD) {
    Mat ret = Mat();
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            ret.mat[i][j] = 0;
            for (int k = 0; k < N; k++) {
                ret.mat[i][j] += (a.mat[i][k] * b.mat[k][j]) % MOD;
                ret.mat[i][j] %= MOD;
            }
        }
    }
    return ret;
}
Mat mat_power(const Mat& m, int y, const int& MOD) {
    Mat x = m, ret = E;
    while (y) {
        if (y & 1) ret = mat_mul(ret, x, MOD);
        x = mat_mul(x, x, MOD);
        y >>= 1;
    }
    return ret;
}
int main() {
#ifndef ONLINE_JUDGE
    FIN;
#endif // ONLINE_JUDGE
    while (~scanf("%d %d", &N, &M) && N) {
        init();
        tmat = Mat();
        while (M --) {
            scanf("%d %d", &s, &t);
            tmat.mat[s][t] = 1;
        }
        scanf("%d", &T);
        while (T --) {
            scanf("%d %d %d", &A, &B, &K);
            res = mat_power(tmat, K, MOD);
            printf("%d\n", res.mat[A][B]);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值