zoukankan      html  css  js  c++  java
  • 51nod 1113 矩阵快速幂

    基准时间限制:3 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
     收藏
     关注
    给出一个N * N的矩阵,其中的元素均为正整数。求这个矩阵的M次方。由于M次方的计算结果太大,只需要输出每个元素Mod (10^9 + 7)的结果。
    Input
    第1行:2个数N和M,中间用空格分隔。N为矩阵的大小,M为M次方。(2 <= N <= 100, 1 <= M <= 10^9)
    第2 - N + 1行:每行N个数,对应N * N矩阵中的1行。(0 <= N[i] <= 10^9)
    Output
    共N行,每行N个数,对应M次方Mod (10^9 + 7)的结果。
    Input示例
    2 3
    1 1
    1 1
    Output示例
    4 4
    4 4

    矩阵快速幂:

    先进性矩阵的乘法,在进行快速幂


    #include<bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    const LL mod=1e9+7;
    int n;
    struct asd{
    	LL a[102][102];
    };
    
    asd mul(asd x,asd y)
    {
    	asd ans;
    	memset(ans.a,0,sizeof(ans.a));
    	for(int i=0;i<n;i++)
    		for(int j=0;j<n;j++)
    			for(int k=0;k<n;k++)
    				ans.a[i][j]=(ans.a[i][j]+x.a[i][k]*y.a[k][j]%mod)%mod;
    	return ans;
    }
    
    asd quickmul(int g,asd x)
    {
    	asd ans;
    	for(int i=0;i<n;i++)
    		for(int j=0;j<n;j++)
    			if(i==j) ans.a[i][j]=1;
    			else ans.a[i][j]=0;
    	while(g)
    	{
    		if(g&1) ans=mul(ans,x);
    		x=mul(x,x);
    		g>>=1;
    	}
    	return ans;
    }
    
    int main()
    {
    	int m;
    	scanf("%d%d",&n,&m);
    	asd x;
    	for(int i=0;i<n;i++)
    		for(int j=0;j<n;j++)
    			scanf("%lld",&x.a[i][j]);
    	x=quickmul(m,x);
    	for(int i=0;i<n;i++)
    	{
    		for(int j=0;j<n;j++)
    		{
    			if(j) printf(" ");
    			printf("%lld",x.a[i][j]);
    		}
    		puts("");
    	}
    	return 0;
    }
    	
    
    



  • 相关阅读:
    并发编程
    进程的介绍
    操作系统详解
    进程的粗略理解
    打印进度条
    FTP上传下载文件(面向对象版)
    socket套接字
    FTP上传下载文件(函数简易版)
    osi七层协议 Open System Interconnection
    __str__和__repr__的区别
  • 原文地址:https://www.cnblogs.com/bryce1010/p/9387104.html
Copyright © 2011-2022 走看看