码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1575-Tr A(矩阵快速幂)

时间:2015-03-04 22:49:57      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

Tr A

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3169    Accepted Submission(s): 2367


Problem Description
A为一个方阵,则Tr A表示A的迹(就是主对角线上各项的和),现要求Tr(A^k)%9973。
 

Input
数据的第一行是一个T,表示有T组数据。
每组数据的第一行有n(2 <= n <= 10)和k(2 <= k < 10^9)两个数据。接下来有n行,每行有n个数据,每个数据的范围是[0,9],表示方阵A的内容。
 

Output
对应每组数据,输出Tr(A^k)%9973。
 

Sample Input
2 2 2 1 0 0 1 3 99999999 1 2 3 4 5 6 7 8 9
 

Sample Output
2 2686
 

Author
xhd
 

矩阵快速幂第一发,以前碰到好几次矩阵快速幂的题,因为这样那样的原因一直没有学,今天拿出来学一下,其实就和快速幂取余的思想差不多。get√

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
using namespace std;
const int inf=0x3f3f3f3f;
const int mod=9973;
int n;
struct node {
    int mp[20][20];
} init,res;
struct node Mult(struct node x, struct node y)// 矩阵相乘
{
    struct node tmp;
    int i,j,k;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++) {
            tmp.mp[i][j]=0;
            for(k=0;k<n;k++)
                tmp.mp[i][j]=(tmp.mp[i][j]+x.mp[i][k]*y.mp[k][j])%mod;
        }
    return tmp;
};
struct node expo(struct node x, int k)//矩阵快速幂
{
    struct node tmp;
    int i,j;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++) {
            if(i==j)
                tmp.mp[i][j]=1;
            else
                tmp.mp[i][j]=0;
        }
    while(k) {
        if(k&1) tmp=Mult(tmp,x);
        x=Mult(x,x);
        k>>=1;
    }
    return tmp;
};
int main()
{
    int T,i,j,k;
    int ans;
    scanf("%d",&T);
    while(T--) {
        scanf("%d %d",&n,&k);
        for(i=0; i<n; i++)
            for(j=0; j<n; j++)
                scanf("%d",&init.mp[i][j]);
        res=expo(init,k);
        ans=0;
        for(i=0; i<n; i++)
            ans=(ans+res.mp[i][i])%mod;
        printf("%d\n",ans);
    }
    return 0;
}



HDU 1575-Tr A(矩阵快速幂)

标签:

原文地址:http://blog.csdn.net/u013486414/article/details/44063785

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!