向前走莫回头❤

【POJ 3233】Matrix Power Series(矩阵快速幂)

Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072K Total Submissions: 21416 Accepted: 8974

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
Source

【题解】【矩阵快速幂】
【这道题,由于范围限制,朴素的矩阵快速幂肯定过不了】
【刚开始想把式子化成 :A(1+A2+A3++Ak1)=>A(1+A(1+A+A2++AK2))=>……=>A(1+A(1+A(1+A)),但还是T】
【借鉴ZYF blog:http://blog.csdn.net/clove_unique/article/details/50733441
这里写图片描述

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
    int d[35][35];
}a,bank,ans;
int n,m,k;
inline node jia(node a,node b)
{
    node c;
    for(int i=1;i<=n;++i)
     for(int j=1;j<=n;++j)
      c.d[i][j]=(a.d[i][j]+b.d[i][j])%m;
    return c;
}
inline node jc(node a,node b)
{
    node c;
    memset(c.d,0,sizeof(c.d));
    for(int i=1;i<=n;++i)
     for(int j=1;j<=n;++j)
      for(int l=1;l<=n;++l)
       c.d[i][j]=(c.d[i][j]+a.d[i][l]*b.d[l][j]%m)%m;
    return c;
}
inline node poww(node b,int p)
{
    node as=bank;
    for(;p;p>>=1,b=jc(b,b))
     if(p&1) as=jc(as,b);
    return as;
}
node solve(int k)
{
    if(k==1) return a;
    int mid=k>>1;
    node now=solve(mid);
    if(k%2==0)
      {
        node x=poww(a,mid);
        x=jia(x,bank);
        x=jc(x,now);
        return x;
      }
     else
      {
        node x=poww(a,mid+1);
        x=jia(x,a);
        x=jc(x,now);
        x=jia(x,a);
        return x;
      }
}
int main()
{
    int i,j;
    scanf("%d%d%d",&n,&k,&m);
    for(int i=1;i<=n;++i)
     for(int j=1;j<=n;++j)
      scanf("%d",&a.d[i][j]);
    for(int i=1;i<=n;++i) bank.d[i][i]=1;
    ans=solve(k);
    for(int i=1;i<=n;++i)
     {
        for(int j=1;j<=n;++j) printf("%d ",ans.d[i][j]);
        printf("\n");
     }
    return 0;
}
posted @ 2016-10-26 16:03  lris0-0  阅读(79)  评论(0编辑  收藏  举报
过去的终会化为美满的财富~o( =∩ω∩= )m