zoukankan      html  css  js  c++  java
  • HDU 1575 Tr A 【矩阵经典2 矩阵快速幂入门】

    任意门:http://acm.hdu.edu.cn/showproblem.php?pid=1575

    Tr A

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


    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
     

     题意概括:如题干

    解题思路:矩阵快速幂(本质是二分优化快速进行幂运算)矩阵快速幂模板题

    注意:单位矩阵初始化

    AC code:

     1 #include <cstdio>
     2 #include <iostream>
     3 #include <cstring>
     4 #include <cmath>
     5 #define LL long long
     6 using namespace std;
     7 const int MAXN = 11;
     8 const int Mod = 9973;
     9 int N;
    10 struct mat
    11 {
    12     int m[MAXN][MAXN];
    13 }base;
    14 
    15 mat muti(mat a, mat b)
    16 {
    17     mat res;
    18     memset(res.m, 0, sizeof(res.m));
    19     for(int i = 1; i <= N; i++)
    20     for(int j = 1; j <= N; j++){
    21             if(a.m[i][j]){
    22                 for(int k = 1; k <= N; k++){
    23                     res.m[i][k] = (res.m[i][k] + a.m[i][j]*b.m[j][k])%Mod;
    24                 }
    25             }
    26         }
    27 
    28     return res;
    29 }
    30 
    31 mat qpow(mat a, int n)
    32 {
    33     mat res;
    34     memset(res.m, 0, sizeof(res.m));
    35     for(int i = 1; i <= N; i++) res.m[i][i] = 1;
    36     while(n){
    37         if(n&1) res = muti(res, a);
    38         n>>=1;
    39         a = muti(a, a);
    40     }
    41     return res;
    42 }
    43 
    44 
    45 int main()
    46 {
    47     int K, T_case;
    48     scanf("%d", &T_case);
    49     while(T_case--){
    50         memset(base.m, 0, sizeof(base.m));
    51         scanf("%d %d", &N, &K);
    52         for(int i = 1; i <= N; i++){
    53             for(int j = 1; j <= N; j++){
    54                 scanf("%d", &base.m[i][j]);
    55             }
    56         }
    57         base = qpow(base, K);
    58         int ans = 0;
    59         for(int i = 1; i <= N; i++){
    60             ans = (ans + base.m[i][i])%Mod;
    61         }
    62         printf("%d
    ", ans);
    63     }
    64 
    65     return 0;
    66 }
    View Code
  • 相关阅读:
    nginx
    同步和异步
    什么是ACID
    关系型数据库特点小结
    js 简单小知识
    join 和 left join 和 right join的区别?
    mysql中having和where区别?
    include和require区别
    什么是脏读,不可重复,幻读?
    Mysql常见面试题
  • 原文地址:https://www.cnblogs.com/ymzjj/p/9926648.html
Copyright © 2011-2022 走看看