ACM: 二分又二分 数论题 poj 3233
来源:互联网 发布:提花组织软件 编辑:程序博客网 时间:2024/06/05 18:24
Matrix Power Series
DescriptionGiven a n × nmatrix A and a positive integer k, find the sumS = A + A2 + A3 +… + Ak.
Input
The input contains exactlyone test case. The first line of input contains three positiveintegers n (n ≤ 30), k (k ≤109) and m (m <104). Then follow n lines each containingn nonnegative integers below 32,768, giving A’selements in row-major order.
Output
Output the elements of S modulo m in the same wayas A is given.
Sample Input
2 2 4
0 1
1 1
Sample Output
1 2
2 3
题意: 计算矩阵A的和, sum = (A + A^2 + A^3 + ... + A^k)%m
解题思路:
1. 式子: sum = A+A^2+A^3+...+A^k
当k是偶数时: 1表示单位矩阵(对角线全为1,其余为0)
sum = (A+A^2+...+A^k)*(1+A^k/2);
当k是奇数时:
sum = (A+A^2+...+A^k/2)*(1+A^k/2+1)+A^k/2+1
2. A^k也是用二分方法求解.
当k是偶数时:
A^k = A^(k/2)*A^(k/2);
当k是奇数时:
A^k = A^(k/2)*A^(k/2)*A;
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 35
struct matrix
{
int row, column;
int g[MAX][MAX];
};
int n, K, m;
matrix a, temp;
inline matrix matrix_add(matrix A, matrix B, int mod)
{
matrix c;
c.row = c.column = A.row;
for(int i = 0; i < c.row; ++i)
{
for(int j = 0; j < c.column; ++j)
{
c.g[i][j] = (A.g[i][j]+B.g[i][j])%mod;
}
}
return c;
}
inline matrix multiply(matrix A, matrix B, int mod)
{
matrix c;
c.row = A.row;
c.column = B.column;
memset(c.g,0,sizeof(c.g));
for(int i = 0; i < A.row; ++i)
{
for(int k = 0; k < A.column; ++k)
{
if(A.g[i][k] != 0)
{
for(int j = 0; j < B.column; ++j)
{
c.g[i][j] = (c.g[i][j]+A.g[i][k]*B.g[k][j])%mod;
}
}
}