zoukankan      html  css  js  c++  java
  • hdu 1575(矩阵快速幂)

    Tr A

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


    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
     
    矩阵快速幂模板题
    #include<stdio.h>
    #include<iostream>
    #include<string.h>
    #include <stdlib.h>
    #include<math.h>
    #include<algorithm>
    using namespace std;
    struct M{
        int v[12][12];
    };
    int n;
    M mult(M a,M b){
        M temp;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                temp.v[i][j] = 0;
                for(int k=0;k<n;k++){
                    temp.v[i][j] = (temp.v[i][j]+a.v[i][k]*b.v[k][j])%9973;
                }
            }
        }
        return temp;
    }
    M pow_mod(M a,int k){
        M ans;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(i==j) ans.v[i][j]=1;
                else ans.v[i][j]=0;
            }
        }
        while(k){
            if(k&1) ans = mult(a,ans);
            a = mult(a,a);
            k>>=1;
        }
        return ans;
    }
    int main(){
        int tcase;
        scanf("%d",&tcase);
        while(tcase--){
            int k ;
            M m;
            scanf("%d%d",&n,&k);
            for(int i=0;i<n;i++){
                for(int j=0;j<n;j++){
                    scanf("%d",&m.v[i][j]);
                }
            }
            M ans = pow_mod(m,k);
            int sum = 0;
            for(int i=0;i<n;i++){
                for(int j=0;j<n;j++){
                    //printf("%d
    ",ans.v[i][j]);
                    if(i==j) sum+=ans.v[i][j];
                }
            }
            printf("%d
    ",sum%9973);
        }
        return 0;
    }
  • 相关阅读:
    Java并发编程笔记——技术点汇总
    Hello Blog
    shell变量
    认识bash这个shell
    使用myeclipse创建带注解的model实体类
    python List,切片的用法
    ignite从0到1的学习过程记录-第一篇:安装和体验
    安卓Service完全解析(中)
    安卓Service完全解析(上)
    JAVA之数组
  • 原文地址:https://www.cnblogs.com/liyinggang/p/5561855.html
Copyright © 2011-2022 走看看