本文主要是介绍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
快速等比数列求和:如何求k=19的情况呢?首先根据19的二进制10011构造这么一阶差分序列:1,2,16,所以原序列是0,1,3,19.
/*79ms,144KB*/#include <cstdio>
#include <cstring>
const int matSize = 31;int calSize = matSize, mod = 1000000007;struct Matrix
{int val[matSize][matSize];Matrix(bool Init = false)///使用默认实参以减少代码量{for (int i = 0; i < calSize; i++){for (int j = 0; j < calSize; j++)val[i][j] = 0;if (Init)val[i][i] = 1;///单位矩阵}}void print(){for (int i = 0; i < calSize; i++){for (int j = 0; j < calSize; j++){if (j)putchar(' ');printf("%d", val[i][j]);}puts("");}}
} Base;Matrix operator + (Matrix &_a, Matrix &_b)
{Matrix ret;for (int i = 0; i < calSize; i++)for (int j = 0; j < calSize; j++)ret.val[i][j] = (_a.val[i][j] + _b.val[i][j]) % mod;return ret;
}Matrix operator * (Matrix &_a, Matrix &_b)
{Matrix ret = Matrix();for (int i = 0; i < calSize; i++)for (int k = 0; k < calSize; k++)if (_a.val[i][k])///优化一下for (int j = 0; j < calSize; j++){ret.val[i][j] += _a.val[i][k] * _b.val[k][j];ret.val[i][j] %= mod;}return ret;
}void deal(int k)
{Matrix one = Matrix(true), ans = Matrix();Matrix ep = Base, tmp = Base, temp;while (k){if (k & 1){ans = ans * ep;ans = ans + tmp;}temp = one + ep;tmp = tmp * temp;ep = ep * ep;k >>= 1;}ans.print();
}int main()
{int k;while (~scanf("%d%d%d", &calSize, &k, &mod)){for (int i = 0; i < calSize; i++)for (int j = 0; j < calSize; j++){scanf("%d", &Base.val[i][j]);Base.val[i][j] %= mod;}deal(k);}return 0;
}
这篇关于POJ 3233 Matrix Power Series (矩阵快速等比数列求和取模)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!