当前位置:网站首页>高斯消元

高斯消元

2022-07-07 07:09:00 moyangxian

bool dcmp(int x, int y, int k) {
    
	if (fabs(a[x][k]) > fabs(a[y][k]))
		return true;
	else if (fabs(a[x][k]) < fabs(a[y][k]))
		return false;
	else {
    
		for (int i = k + 1; i <= n; i++)
			if (fabs(a[x][i]) < fabs(a[y][i])) return true;
		return false;
	}
}

//0表示有无穷解,1表示有唯一解
//测试洛谷P3389
int Gauss() {
    
	for (int r = 1, c = 1; c <= n; c++, r++) {
    
		int t = r;
		for (int i = r + 1; i <= n; i++)
			if (fabs(a[i][c]) > fabs(a[t][c]))
				t = i;
		if (sgn(a[t][c]) == 0) return 0;
		if (t != r)for (int i = c; i <= n + 1; i++)swap(a[t][i], a[r][i]);
		for (int i = n + 1; i >= c; i--)a[r][i] /= a[r][c];
		for (int i = 1; i <= n; i++)
			if (i != r) {
    
				for (int j = c + 1; j <= n + 1; j++)
					a[i][j] -= a[r][j] * a[i][c];
				a[i][c] = 0;
			}
	}
	return 1;
}

//-1表示无解,0表示有无穷解,1表示有唯一解
//测试洛谷P2455
int Gauss() {
    
	for (int r = 1, c = 1; c <= n; c++, r++) {
    
		int t = r;
		for (int i = r + 1; i <= n; i++)
			if (dcmp(i, t, c)) t = i;
		if (t != r) for (int i = c; i <= n + 1; i++) swap(a[t][i], a[r][i]);
		if (sgn(a[r][c]) == 0) continue;
		for (int i = n + 1; i >= c; i--) a[r][i] /= a[r][c];
		a[r][c] = 1;
		for (int i = 1; i <= n; i++) {
    
			if (i == r) continue;
			for (int j = c + 1; j <= n + 1; j++)
				a[i][j] -= a[r][j] * a[i][c];
			a[i][c] = 0;
		}
	}
	bool f1 = 0, f2 = 0;
	for (int i = 1; i <= n; i++) {
    
		if (sgn(a[i][i]) == 0 && sgn(a[i][n + 1]) != 0) f1 = 1;
		if (sgn(a[i][i]) == 0 && sgn(a[i][n + 1]) == 0) f2 = 1;
	}
	if (f1) return -1;   //无解
	if (f2) return 0;    //无穷多解
	return 1;   //唯一解
}
原网站

版权声明
本文为[moyangxian]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_45809826/article/details/116451089