HDU 1575 Tr A (矩阵快速幂入门)

来源:互联网 发布:淘宝店铺重新激活 编辑:程序博客网 时间:2024/06/05 03:08

题意就不多说了,一道基础的矩阵入门。

#include "stack"#include "cstdio"#include "iostream"#include "cmath"#include "set"#include "sstream"#include "cctype"#include "string"#include "cstring"#include "algorithm"#include "queue"#include "map"using namespace std;#define LL long long#define inf 0x3f3f3f3f#define pa pair<int,int>#define pi 3.1415926535897932384626433832795028841971#define max 12const int M=5000;struct node{    int map[max][max];}st,ed;int n,k;node mat_mul(node a,node b){    node tem;    for(int i=0; i<n; i++)        for(int j=0; j<n; j++)        {            tem.map[i][j]=0;            for(int h=0; h<n; h++)                tem.map[i][j]+=a.map[i][h]*b.map[h][j];   //矩阵相乘              tem.map[i][j]%=9973;        }    return tem;}int qu_sum()//二分法矩阵求幂{    node tem1=st,tem2=ed;    while(k!=1)    {        if(k%2)   //判断奇偶进行不同处理        {            k--;            tem1=mat_mul(tem1,tem2);          //k=20 10 5(奇数) 2 1        }        else        {            k>>=1;            tem2=mat_mul(tem2,tem2);        }    }    node ans=mat_mul(tem1,tem2);    int sum=0;    for(int j=0; j<n; j++)    {        sum+=ans.map[j][j];        sum%=9973;    }    return sum;}int main(){    int T,i,j;    scanf("%d",&T);    while(T--)    {        memset(st.map,0,sizeof(st.map));        scanf("%d%d",&n,&k);        for(i=0; i<n; i++)            for(j=0; j<n; j++)            {                                   st.map[i][j]=0;                st.map[i][i]=1;  //单位矩阵                scanf("%d",&ed.map[i][j]);            }        printf("%d\n",qu_sum());    }    return 0;}


 

 

 

0 0
原创粉丝点击