hdu2157 How many ways?? 矩阵快速幂

while (cin>>n>>m,n!=0||m!=0)
而不是
while (cin>>n>>m,n!=0&&m!=0)
这个卡了半天我靠……

一样的模板

依然是构造变换矩阵左乘向量

变换矩阵是图矩阵的转置。为啥,因为我凑出来是这样的……

向量保存的是到某个点的方法总数

乘k个变换矩阵,目标点对应的在向量中的数即为结果。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<fstream>
#include<algorithm>
#include<map>
#include<vector>
#include<cmath>
using namespace std;
#define ll long long
//Template mat
//Interface here
#define MULMOD
//Use mat(int row,int cow) to define a new EMPTY mat
//Use define MULMOD and set MOD to ENABLE MOD
#define MAXROWS 21
#define MAXCOLS 21
#ifdef MULMOD
int MOD;
#endif
//Interface End

struct Matrix
{
    int Rows,Cols;
    ll data[MAXROWS][MAXCOLS];
    void clear()
    {
        memset(data,0,sizeof(data));
    }
    Matrix (int n,int m)
    :Rows(n),Cols(m)
    {
        clear();
    }
    Matrix (int n)
    :Rows(n),Cols(n)
    {
        clear();
        for (int i=0;i<n;i++)
            data[i][i]=1;
    }
    ll* operator[](const int n)
    {
        return data[n];
    }
    Matrix operator* (const Matrix& ano) const
    {
        Matrix result(Rows,ano.Cols);
        for (int i=0;i<Rows;i++)
            for (int j=0;j<ano.Cols;j++)
                for (int k=0;k<Cols;k++)
                {
                    #ifdef MULMOD
                    result[i][j] += data[i][k] * ano.data[k][j] % MOD;
                    result[i][j]%=MOD;
                    #else
                    result[i][j] += data[i][k] * ano.data[k][j];
                    #endif
                }
        return result;
    }
};
Matrix QuickMatrixPow(Matrix to ,int k)
{
    Matrix ans(to.Rows);
    while (k)
    {
        if (k&1)
            ans=ans*to;
        k>>=1;
        to = to*to;
    }
    return ans;
}
//Template mat end

int main()
{
    cin.sync_with_stdio(false);
    int n,m;
    //fstream testf("test.txt");
    //cin.rdbuf(testf.rdbuf());
    MOD=1000;
    while (cin>>n>>m,n!=0||m!=0)
    {
        int tp1,tp2;
        Matrix A(n,n);
        for (int i=0;i<m;i++)
        {
            cin>>tp1>>tp2;
            A[tp2][tp1]=1;
        }
        cin>>tp1;
        int tp3,tp4;
        for (int i=0;i<tp1;i++)
        {
            Matrix V0(n,1);
            cin>>tp2>>tp3>>tp4;
            V0[tp2][0]=1;
            cout<< (QuickMatrixPow(A,tp4) * V0 ) [tp3][0] <<endl;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值