poj 3233 待提交 Matrix Power Series


Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072K
Total Submissions: 16403 Accepted: 6980

Description

Given a n × n matrix A and a positive integerk, find the sumS =A + A2 + A3 + … +Ak.

Input

The input contains exactly one test case. The first line of input contains three positive integersn (n ≤ 30),k (k ≤ 109) andm (m < 104). Then follownlines each containingn nonnegative integers below 32,768, givingA’s elements in row-major order.

Output

Output the elements of S modulo m in the same way asA is given.

Sample Input

2 2 4
0 1
1 1

Sample Output

1 2
2 3

Source

POJ Monthly--2007.06.03, Huang, Jinsong

题目链接: http://poj.org/problem?id=3233

题目大意:就是求 S =  A +  A 2 + A 3 + … + Ak

题目分析:分析可以得到
k为偶数:sum(k) = (1+A^(k/2)) *( A+A^2+……+A^(k/2)) = (1+A^(k/2)) * sum(k/2)
k为奇数:sum(k) = (1+A^((k-1)/2)) * sum(k/2) + A^k

A的几次方快速幂可求
但求的是A^1加到A^k,k十分大
这个还是采取二分思想
先算出来A^1+A^2+..A^(k/2)
再总体乘以(I+A^(k/2)),若k为奇数再加上A^k即可
#include <iostream>
#include <string.h>
using namespace std;
int n,k,mod;
struct matrix
{
    long long e[31][31];
}a,x,y;
matrix matrix_mul(matrix a1,matrix b)
{
    matrix sum;
    memset(sum.e,0,sizeof(sum.e));
    for(int i=0;i<n;++i)
    for(int j=0;j<n;++j)
    for(int k=0;k<n;++k)//因为写成i<n改了半个小时 mmp
    if(a1.e[i][k]&&b.e[k][j])
    sum.e[i][j]=(sum.e[i][j]+a1.e[i][k]*b.e[k][j])%mod;
    return sum;
}
matrix matrix_pow(int p)
{

    memset(y.e,0,sizeof(y.e));
    for(int i=0;i<n;++i)
        y.e[i][i]=1;
      while(p)
      {
          if(p&1)
             y=matrix_mul(y,a);
          p>>=1;
             a=matrix_mul(a,a);
      }
    return y;
}
void add()
{
    matrix ans,aa,ak;
    ans=matrix_pow(1);
    for(int i=2;i<=k/2;++i)
    {
        aa=matrix_pow(i);
        for(int j=0;j<n;++j)
            for(int t=0;t<n;++t)
            ans.e[j][t]=(ans.e[j][t]+aa.e[j][t])%mod;
    }
   if(k!=1)
    {
        ak=matrix_mul(ans,y);
        for(int j=0;j<n;++j)
            for(int t=0;t<n;++t)
            ans.e[j][t]=(ans.e[j][t]+ak.e[j][t])%mod;
    }
    if(k%2)
    {
        ak=matrix_pow(k);
        for(int j=0;j<n;++j)
            for(int t=0;t<n;++t)
            ans.e[j][t]=(ans.e[j][t]+ak.e[j][t])%mod;
    }
    for(int j=0;j<n;++j)
    {
      for(int t=0;t<n;++t)
        cout<<ans.e[j][t]<<' ';
        cout<<endl;
    }
    cout<<endl;
}
int main()
{
    cin>>n>>k>>mod;
    for(int i=0;i<n;++i)
        for(int j=0;j<n;++j)
        cin>>a.e[i][j];
    add();
    return 0;
}
不得不佩服人家的编程功底:http://blog.csdn.net/tc_to_top/article/details/43878231
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值