数论-矩阵快速幂模版

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define M 20

int num, mod;

//定义矩阵结构体
struct mat
{
    int at[M][M];
};
struct mat d;

//a,b矩阵互乘;
mat mul(mat a, mat b)
{
    mat t;
    memset(t.at, 0, sizeof(t.at));
    for(int i=0;i<num;i++)
        for(int k=0;k<num;k++)
            if(a.at[i][k])
                for(int j=0;j<num;j++)            
                    t.at[i][j]=(t.at[i][j]+a.at[i][k]*b.at[k][j])%mod;                        
    return t;
}

//矩阵自乘K次;
mat expo(mat p, int k)
{
    if(k==1)
        return p;
    mat e;
    memset(e.at, 0, sizeof(e.at));
    for(int i=0;i<num;i++)
        e.at[i][i]=1;
    if(k==0)
        return e;
    while(k)
    {
        if(k & 1)
            e=mul(p, e);
        p=mul(p, p);
        k>>=1;
    }
    return e;
}

int main()
{
    int t;
    int k, m, a, b, x, y, n;
    int ans;
    mat ret;

    while(scanf("%d%d", &t,&n)!=EOF)
    {
        memset(d.at, 0, sizeof(d.at));

        if(t==0&&n==0) break;

        num=t;
        
        while(n--)
        {
            scanf("%d%d", &a, &b);
            d.at[a][b]=1;
        }

        scanf("%d",&m);

        while(m--)
        {
            scanf("%d%d%d",&x,&y,&k);
            mod=1000;
            ret=expo(d, k);            //矩阵d自乘k次
            ans=ret.at[x][y]%mod;
            printf("%d
", ans);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/mochenmochen/p/5156837.html