南邮1340 矩阵逆 初等行转换

题目链接; noj1340



好长时间没写博客了, 今天刚学矩阵逆, 找到裸题, 试试, 嘿嘿



题解: 初等行转换, (A, E) -> (E, A^-1);


code:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
using namespace std;


const int maxn = 100 + 5;

int n, word;
vector<double> a[maxn], c[maxn], t[maxn];double  temp;

inline vector<double> operator * (vector<double>a, double b) {
	vector<double> res(n, 0);
	for (int i = 0; i < n; i++)
		res[i] = a[i] * b;
	return res;
}

inline vector<double> operator - (vector<double>a, vector<double> b) {
	vector<double> res(n, 0);
	for (int i = 0; i < n; i++)
		res[i] = a[i] - b[i];
	return res;
}
inline void inverse() {
	for (int i = 0; i < n; i++)
		c[i] = vector<double>(n, 0);
	for (int i = 0; i < n; i++)
		c[i][i] = 1;
	for (int i = 0; i < n; i++) {
		word = 0;
		for (int j = i; j < n; j++) {
			if (fabs(a[j][i]) > 0) {
				word = 1;
				swap(a[i], a[j]);
				swap(c[i], c[j]);
				break;
			}
		}//printf("word : %d\n", word);
		if (!word)
			return;
		c[i] = c[i] * (1 / a[i][i]);
		a[i] = a[i] * (1 / a[i][i]);
		for (int j = 0; j < n; j++) {
			if (j != i && fabs(a[j][i]) > 0) {
				c[j] = c[j] - c[i] * a[j][i];
				a[j] = a[j] - a[i] * a[j][i];
			}
		}
	}
}
int main() {
	//freopen("in.txt", "r", stdin);
	while (~scanf("%d", &n)) {
		//printf("%d\n", n);
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++) {
				scanf("%lf", &temp);
				a[i].push_back(temp);
			}
		}
		inverse();
		/*for (int i = 0; i < n; i++)
		{
			//a[i](n, 0);
			for (int j = 0; j < n; j++)
				printf("  %lf", c[i][j]);
			puts("");
		}*/
		for (int i = 0; i < n; i++)
		{
			//a[i](n, 0);
			for (int j = 0; j < n; j++) {
				scanf("%lf", &temp);
				t[i].push_back(temp);
			}
		}
		if (word) {
			for (int i = 0; i < n; i++)
			{
				//a[i](n, 0);
				for (int j = 0; j < n; j++)
				{
					//printf("%lf, %lf\n", t[i][j], c[i][j]);
					if (fabs(t[i][j] - c[i][j]) > 1e-6)
					{
						word = 0;
						break;
					}
				}
				if (!word)
					break;
			}
			printf("%s\n", word ? "YES" : "NO");
		}
		else {
			printf("NO\n");
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值