poj 3233(矩阵快速幂)

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

在做了矩阵快速幂的入门之后,又做了这道题,发现好难呀,特别是找转移式子很难推,这次的题又用到了二分+快速幂,用的很巧妙,多看几遍就会了

#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<stdio.h>
using namespace std;
int n,m;
struct uuu
{
    int u[50][50];
}s,v;
uuu mult(uuu x,uuu y)
{
    uuu ans;
    memset(ans.u,0,sizeof(ans.u));
    for(int a=0;a<n;a++)
    {
        for(int b=0;b<n;b++)
        {
            for(int k=0;k<n;k++)
            ans.u[a][b]=(ans.u[a][b]+x.u[a][k]*y.u[k][b])%m;
        }
    }
    return ans;
}
uuu poww(uuu s,int k) 
{
    uuu ans;
    for(int a=0;a<n;a++)
    {
        for(int b=0;b<n;b++)
        {
            if(a==b)
            {
                ans.u[a][b]=1;
            }
            else
                ans.u[a][b]=0;
        }
    }
    while(k)
    {
        if(k&1)
            ans=mult(ans,s);

        s=mult(s,s);
        k>>=1;
    }
    return ans;
}
uuu add(uuu x,uuu y)
{
    uuu ans;
    for(int a=0;a<n;a++)
    {
        for(int b=0;b<n;b++)
            ans.u[a][b]=(x.u[a][b]+y.u[a][b])%m;
    }
    return ans;
}
uuu sum(uuu s,int k)
{
    uuu temp,y;
    if(k==1)return s;
    temp=sum(s,k/2);
    if(k&1)
    {
        y=poww(s,k/2+1);
        temp=add(temp,mult(temp,y));
        return add(temp,y);
    }
    else
    {
        y=poww(s,k/2);
        temp=add(mult(y,temp),temp);
        return temp;
    }
}
int main()
{
    int k,x;
    scanf("%d%d%d",&n,&k,&m);
    for(int a=0;a<n;a++)
    {
        for(int b=0;b<n;b++)
        {
            scanf("%d",&x);
            s.u[a][b]=x%m;
        }
    }
    v=sum(s,k);
    for(int a=0;a<n;a++)
    {
        for(int b=0;b<n;b++)
        {
            printf("%d",v.u[a][b]);
            if(b!=n-1)
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值