POJ 3233 -- Matrix Power Series



POJ 3233 -- Matrix Power Series
Description
Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.
Input
The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.
Output
Output the elements of S modulo m in the same way as A is given.
Sample Input
2 2 4
0 1
1 1
Sample Output
1 2
2 3

http://www.abandonzhang.com/archives/484

题目给定一个n*n的矩阵A,要求(A+A^2+....A^K)%m后的矩阵
①二分
这种方法我觉得与秦九韶算法计算多项式的思路类似,都是找出重复因子而减少多项式计算的次数.当然我们这个多项式比较特殊,所以有比秦九韶算法更好的思路:

当k为偶数时:
S(k) = A^1+A^2+A^3 + A^(k/2) + A^(k/2+1) + …… + A^(k/2+k/2)
= (A^(k/2) + E) (A^1 + A^2 + A^3 …… + A^(k/2) )
=(A^(k/2) + E) * S(k/2)
当k为奇数时:
S(k) = S(k-1) * A^k
const int MAX = 30;
struct Mat{
    int row, col;
    LL mat[MAX][MAX];
};
//initialize square matrix to unit matrix
Mat unit(int n){
    Mat A;
    A.row = A.col = n;
    memset(A.mat, 0, sizeof(A.mat));
    for (int i = 0; i < n; i ++)
        A.mat[i][i] = 1;
    return A;
}
//return T(A)
Mat transpose(Mat A){
    Mat T;
    T.row = A.col;
    T.col = A.row;
    for (int i = 0; i < A.col; i ++)
        for (int j = 0; j < A.row; j ++)
            T.mat[i][j] = A.mat[j][i];
    return T;
}
//return (A+B)%mod
Mat add(Mat A, Mat B, int mod){
    Mat C = A;
    for (int i = 0; i < C.row; i ++)
        for (int j = 0; j < C.col; j ++)
            C.mat[i][j] = (A.mat[i][j] + B.mat[i][j]) % mod;
    return C;
}
//return A*B%mod
Mat mul(Mat A, Mat B, int mod){
    Mat C;
    C.row = A.row;
    C.col = B.col;
    for (int i = 0; i < A.row; i ++){
        for (int j = 0; j < B.col; j ++){
            C.mat[i][j] = 0;
            for (int k = 0; k < A.col; k ++)
                //注意这里要保证乘法不溢出,否则还需要设计特殊的乘法模
                C.mat[i][j] += A.mat[i][k] * B.mat[k][j];
            C.mat[i][j] %= mod;
        }
    }
    return C;
};
//return A^n%mod
Mat exp_mod(Mat A, int n, int mod){
    Mat res = unit(A.row);
    while(n){
        if (n & 1){
            res = mul(res, A, mod);
        }
        A = mul(A, A, mod);
        n >>= 1;
    }
    return res;
}

Mat A;
int n, k, mod;
Mat S(int k){
    if (k == 1){
        return A;
    }
    if (k % 2 == 0){
        return mul(add(exp_mod(A, k/2, mod), unit(n), mod), S(k/2), mod);
    }
    else{
        return add(S(k-1), exp_mod(A, k, mod), mod);
    }
}
int main(){
    cin >> n >> k >> mod;
    A.row = A.col = n;
    for (int i = 0; i < n; i ++)
        for (int j = 0; j < n; j ++)
            cin >> A.mat[i][j];
    Mat ans = S(k);
    for (int i = 0; i < ans.row; i ++){
        for (int j = 0; j < ans.col - 1; j ++)
            cout << ans.mat[i][j] << " ";
        cout << ans.mat[i][ans.col-1] << endl;
    }
 return 0;
}
②线性变换(很赞的一种方法呐~!涨姿势~)
我们考虑递推,即从s(k-1)到s(k)的线性变换。
首先一维线性变换显然是出不来的,就像A^1+A^2+A^3+……+A^k = d * (A^1+A^2+A^3+……+A^(k-1)  ) 明显不行……

那么我们再加一维就显然了:

A^1+A^2+A^3+……+A^k =( A^1+A^2+A^3+……+A^(k-1)  ) + A^k

A^(k+1) = 0 * ( A^1+A^2+A^3+……+A^(k-1)  ) + A * A^k.        //这一行的变换是作为辅助,补全二维的线性变换.
那么线性变换矩阵B显然就是:
1 1
0 1

一般化就有
s(k)                    1  1             s(k-1)
A^k+1     =     0  1     *     A^k
即P(k) = B^(n-1) * P(1)
const int MAX = 60;
struct Mat{
    int row, col;
    LL mat[MAX][MAX];
};
//initialize square matrix to unit matrix
Mat unit(int n){
    Mat A;
    A.row = A.col = n;
    memset(A.mat, 0, sizeof(A.mat));
    for (int i = 0; i < n; i ++)
        A.mat[i][i] = 1;
    return A;
}
//return T(A)
Mat transpose(Mat A){
    Mat T;
    T.row = A.col;
    T.col = A.row;
    for (int i = 0; i < A.col; i ++)
        for (int j = 0; j < A.row; j ++)
            T.mat[i][j] = A.mat[j][i];
    return T;
}
//return (A+B)%mod
Mat add(Mat A, Mat B, int mod){
    Mat C = A;
    for (int i = 0; i < C.row; i ++)
        for (int j = 0; j < C.col; j ++)
            C.mat[i][j] = (A.mat[i][j] + B.mat[i][j]) % mod;
    return C;
}
//return A*B%mod
Mat mul(Mat A, Mat B, int mod){
    Mat C;
    C.row = A.row;
    C.col = B.col;
    for (int i = 0; i < A.row; i ++){
        for (int j = 0; j < B.col; j ++){
            C.mat[i][j] = 0;
            for (int k = 0; k < A.col; k ++)
                //注意这里要保证乘法不溢出,否则还需要设计特殊的乘法模
                C.mat[i][j] += A.mat[i][k] * B.mat[k][j];
            C.mat[i][j] %= mod;
        }
    }
    return C;
};
//return A^n%mod
Mat exp_mod(Mat A, int n, int mod){
    Mat res = unit(A.row);
    while(n){
        if (n & 1){
            res = mul(res, A, mod);
        }
        A = mul(A, A, mod);
        n >>= 1;
    }
    return res;
}

Mat A;
int n, k, mod;

int main(){
    cin >> n >> k >> mod;
    A.row = A.col = n;
    for (int i = 0; i < n; i ++)
        for (int j = 0; j < n; j ++)
            cin >> A.mat[i][j];

    Mat res;
    res.row = 2 * n;
    res.col = n;
    for (int i = 0; i < n; i ++)
        for (int j = 0; j < n; j ++)
            res.mat[i][j] = A.mat[i][j];
    for (int i = n; i < 2 * n; i ++)
        for (int j = 0; j < n; j ++)
            res.mat[i][j] = A.mat[i-n][j];

    Mat E = unit(n);

    Mat B;
    memset(B.mat, 0, sizeof(B.mat));
    B.row = B.col = 2 * n;
    for (int i = 0; i < n; i ++){
        for (int j = 0; j < n; j ++)
            B.mat[i][j] = E.mat[i][j];
        for (int j = n; j < 2 * n; j ++)
            B.mat[i][j] = A.mat[i][j-n];
    }
    for (int i = n; i < 2 * n; i ++){
        for (int j = n; j < 2 * n; j ++)
            B.mat[i][j] = A.mat[i-n][j-n];
    }
    B = exp_mod(B, k-1, mod);
    res = mul(B, res, mod);
    for (int i = 0; i < n; i ++){
        for (int j = 0; j < n - 1; j ++)
            cout << res.mat[i][j] << " ";
        cout << res.mat[i][n-1] << endl;
    }
    return 0;
}
对于任意的A^x,我们都能够利用矩阵快速幂求出,但是我们现在要求的是和。
   仔细观察整个式子,那么我们可以对原式进行变形
   如果k为偶数,那么(A+A^2+....A^K) = (A+...+A^K/2)+A^K/2*(A+...+A^K/2)
   如果k为奇数,那么(A+A^2+....A^K) = (A+...+A^K/2)+A^K/2*(A+...+A^K/2)+A^k

3 那么对于上面的式子的变形,就是二分的思想,那么我们可以利用二分来求和,然后对于单个的矩阵的x次方我们利用快速幂
思路:矩阵快速幂。首先我们知道 A^x 可以用矩阵快速幂求出来(具体可见poj 3070)。其次可以对k进行二分,每次将规模减半,分k为奇偶两种情况,如当k = 6和k = 7时有:
      k = 6 有: S(6) = (1 + A^3) * (A + A^2 + A^3) = (1 + A^3) * S(3)。
      k = 7 有: S(7) = A + (A + A^4) * (A + A^2 + A^3) = A + (A + A^4) * S(3)。


ps:对矩阵定义成结构体Matrix,求S时用递归,程序会比较直观,好写一点。当然定义成数组,然后再进行一些预处理,效率会更高些。

  1. const int N = 30;  
  2.   
  3. int n , k , MOD;  
  4. struct Matrix{  
  5.     int mat[N][N];  
  6.     Matrix operator*(const Matrix& m)const{  
  7.         Matrix tmp;  
  8.         for(int i = 0 ; i < n ; i++){  
  9.             for(int j = 0 ; j < n ; j++){  
  10.                 tmp.mat[i][j] = 0;  
  11.                 for(int k = 0 ; k < n ; k++)  
  12.                     tmp.mat[i][j] += mat[i][k]*m.mat[k][j]%MOD;  
  13.                 tmp.mat[i][j] %= MOD;  
  14.             }  
  15.         }  
  16.         return tmp;  
  17.     }  
  18.     Matrix operator+(const Matrix& m)const{  
  19.         Matrix tmp;  
  20.         for(int i = 0 ; i < n ; i++)  
  21.             for(int j = 0 ; j < n ; j++)  
  22.                 tmp.mat[i][j] = (mat[i][j]+m.mat[i][j])%MOD;  
  23.         return tmp;  
  24.     }  
  25. };  
  26.   
  27. Matrix Pow(Matrix m , int t){  
  28.     Matrix ans;  
  29.     memset(ans.mat , 0 , sizeof(ans.mat));  
  30.     for(int i = 0 ; i < n ; i++)  
  31.         ans.mat[i][i] = 1;  
  32.     while(t){  
  33.         if(t&1)  
  34.             ans = ans*m;  
  35.         t >>= 1;  
  36.         m = m*m;  
  37.     }  
  38.     return ans;  
  39. }  
  40.   
  41. Matrix solve(Matrix m , int t){  
  42.     Matrix A;  
  43.     memset(A.mat , 0 , sizeof(A.mat));  
  44.     for(int i = 0 ; i < n ; i++)  
  45.         A.mat[i][i] = 1;  
  46.     if(t == 1)  
  47.         return m;  
  48.     if(t&1)  
  49.         return (Pow(m,t>>1)+A)*solve(m,t>>1)+Pow(m , t);         
  50.     else  
  51.         return (Pow(m,t>>1)+A)*solve(m,t>>1);         
  52. }  
  53.   
  54. void output(Matrix ans){  
  55.     for(int i = 0 ; i < n ; i++){  
  56.         printf("%d" , ans.mat[i][0]%MOD);  
  57.         for(int j = 1 ; j < n ; j++)  
  58.             printf(" %d" , ans.mat[i][j]%MOD);  
  59.         puts("");  
  60.     }  
  61. }  
  62.   
  63. int main(){  
  64.     Matrix m , ans;  
  65.     while(scanf("%d%d%d" , &n , &k , &MOD) != EOF){  
  66.          for(int i = 0 ; i < n ; i++)  
  67.             for(int j = 0 ; j < n ; j++)  
  68.                 scanf("%d" , &m.mat[i][j]);  
  69.          ans = solve(m , k);  
  70.          output(ans);  
  71.     }  
  72.     return 0;  
  73. }  
http://xufz.wordpress.com/2013/12/21/poj-3233-matrix-power-series/
先把形式写成 Sk = A + A2 + A3 + … + Ak, 然后容易看出
Sk = Sk/2 × Ak/2 + Sk/2+ (Ak if odd k)
这样的解法用矩阵快速幂已经可以通过,但是每次还要矩阵加法。
因为 Ak = A × Ak-1,如果把 A 看成常数,然后 Sk 也用 Sk-1 和 Ak-1 表示出来,就可以把数列的递推式用矩阵表示。
于是 Sk= A × Ak-1 + Sk-1,所以
20131222033400
这样只要算一个快速幂就好了,矩阵规模被扩大了两倍,但是根据这个矩阵的特点算乘法的时候可以做些优化


Read full article from 3233 -- Matrix Power Series

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts