zoukankan      html  css  js  c++  java
  • poj3233

    (g++比c++快不少

    分治+矩阵快速幂

    #include<iostream>
    #include<cstdio>
    #include<queue>
    #include<algorithm>
    #include<cmath>
    #include<cstring>
    #define inf 2147483647
    #define N 1000010
    #define p(a) putchar(a)
    #define For(i,a,b) for(register long long i=a;i<=b;++i)
    
    using namespace std;
    long long n,k,m;
    
    struct matrix{
        long long a[40][40];
        matrix operator * (const matrix & b) const{
            matrix r;
            For(i,1,n)
                For(j,1,n){
                    r.a[i][j]=0;
                    For(k,1,n)
                        r.a[i][j]+=a[i][k]*b.a[k][j]%m;
                        r.a[i][j]%=m;
                }
            return r;
        }
    }init;
    
    void in(long long &x){
        long long y=1;char c=getchar();x=0;
        while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
        while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
        x*=y;
    }
    void o(long long x){
        if(x<0){p('-');x=-x;}
        if(x>9)o(x/10);
        p(x%10+'0');
    }
    
    matrix ksm(matrix a,long long k){
        matrix r=a;k--;
        if(k==0)
            return r;
        while(k>0){
            if(k%2==1)
                r=r*a;
            a=a*a;
            k>>=1;
        }
        return r;
    }
    
    matrix add(matrix A,matrix B){
        matrix r;
        For(i,1,n)
            For(j,1,n)
                r.a[i][j]=(A.a[i][j]+B.a[i][j])%m;
        return r;
    }
    
    matrix sum(matrix a,long long k){
        if(k==1)
            return a;
        matrix half,t,temp;
        half=sum(a,k>>1);
        if(k&1){
            t=ksm(a,(k>>1)+1);
            temp=half*t;
            return add(add(half,temp),t);
        }
        else{
            t=ksm(a,k>>1);
            temp=half*t;
            return add(temp,half);
        }
    }
    
    int main(){
        in(n);in(k);in(m);
        For(i,1,n)
            For(j,1,n){
                in(init.a[i][j]);
                init.a[i][j]%=m;
            }
        matrix r;
        r=sum(init,k);
        For(i,1,n){
            For(j,1,n)
                o(r.a[i][j]),p(' ');
            p('
    ');
        }
        return 0;
    }
  • 相关阅读:
    Resample the mask
    高斯消元法
    java中的大数BigInteger
    JAVA中如何使用SORT从大到小排
    Java中Array.sort()的几种用法简明教程 (需要初始化要排序的对象)
    java中两个字符串如何比较大小
    java数组初始化函数
    BestCoder Round #89 Fxx and string
    Flooded!
    基础练习 数列排序
  • 原文地址:https://www.cnblogs.com/war1111/p/11277813.html
Copyright © 2011-2022 走看看