POJ 3233 (矩阵)

题意:对于矩阵A,求A^1 + ...... + A^k

按照矩阵十大经典题的思路大致做了下。

在k为奇数时:  A^( k / 2+1)+ 1) * (A^1 + ....... A^(k/2)) + A^(k/2+1)

k为偶数时:(A^(k/2) + 1 )* (A^1 + ................A^(k/2))

但是超时了,应该是没二分的问题。



#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<string>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#include<functional>
using namespace std;
typedef long long ll;

const int maxn=5e5;
map<int,int>has;
struct Matrix
{
    int xmap[30][30];
};
int siz;
Matrix mat;
int n,mod;
Matrix Mul(const Matrix &a,const Matrix &b)
{
    Matrix c;
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            c.xmap[i][j]=0;
            for(int k=0; k<n; k++)
            {
                c.xmap[i][j]+=a.xmap[i][k]*b.xmap[k][j];
                c.xmap[i][j]%=mod;
            }
        }
    }
    return c;
}

Matrix Pow(int n)
{
    if(n == 1)
        return mat;
    else if(n & 1)
    {
        return Mul(mat,Pow(n-1));
    }
    else
    {
        Matrix tmp = Pow(n>>1);
        return Mul(tmp,tmp);
    }
}

Matrix Add(const Matrix &a,const Matrix &b)
{
    Matrix c;
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            c.xmap[i][j] = a.xmap[i][j] + b.xmap[i][j];
            c.xmap[i][j]%=mod;
        }
    }
    return c;
}

Matrix solve(int k)
{
    if(k == 1)
        return mat;
    Matrix tt;
    Matrix tmp = solve(k/2);
    if (k&1)
    {
        tt=Pow(k/2+1);
        tmp=Add(tmp,Mul(tmp,tt));
        tmp=Add(tt,tmp);
    }
    else
    {
        tt=Pow(k/2);
        tmp=Add(tmp,Mul(tmp,tt));
    }
    return tmp;
}

int main()
{
    int k;
    while(scanf("%d%d%d",&n,&k,&mod)!= EOF)
    {
        for(int i = 0; i < n; i++)
            for(int j = 0 ; j < n; j++)
            {
                scanf("%d",&mat.xmap[i][j]);
                mat.xmap[i][j] %= mod;
            }

        Matrix ans = solve(k);
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < n; j++)
                printf("%d ",ans.xmap[i][j]);
            printf("
");
        }
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/Przz/p/5409750.html