码迷,mamicode.com
首页 > 编程语言 > 详细

蓝桥杯 BASIC 27 矩阵乘法(矩阵、二维数组)

时间:2015-03-20 00:00:06      阅读:382      评论:0      收藏:0      [点我收藏+]

标签:acm   蓝桥杯   

【思路】:注意0次幂是单位矩阵。

【AC代码】:

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstdio>
#include <cstring>
using namespace std;

#define MAX 30+2

void cal(int m[MAX][MAX], int t[MAX][MAX], int r[MAX][MAX], int N)
{
	int i = 0, j = 0, k = 0;
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < N; j++)
		{
			int temp = 0;
			for (k = 0; k < N; k++)
			{
				temp += m[i][k] * t[k][j];
			}
			r[i][j] = temp;
		}
	}
}

void copy(int t[MAX][MAX], int r[MAX][MAX], int N)
{
	int i = 0, j = 0;
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < N; j++)
		{
			t[i][j] = r[i][j];
		}
	} 
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	int N = 0, M = 0, matrix[MAX][MAX], temp[MAX][MAX], res[MAX][MAX];
	int i = 0, j = 0;
	
	//input
	cin >> N >> M;
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < N; j++)
		{
			cin >> matrix[i][j];
			if (i == j)
			{
				temp[i][j] = 1;
				res[i][j] = 1;
			}
			else
			{
				temp[i][j] = 0;
				res[i][j] = 0;
			}
		}
	}
	
	//cal
	for (i = 0; i < M; i++)
	{
		cal(matrix, temp, res, N);
		copy(temp, res, N);
	}
	
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < N; j++)
		{
			cout << res[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}


蓝桥杯 BASIC 27 矩阵乘法(矩阵、二维数组)

标签:acm   蓝桥杯   

原文地址:http://blog.csdn.net/weijj6608/article/details/44469395

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!