高斯消元 n^3
作者:互联网
void gauss()
{
// 转化成上三角矩阵
for (int r = 1, c = 1; c <= n; c ++, r ++ )//枚举行
{
// 找主元 一列里面找绝对值最大
int t = r;
for (int i = r + 1; i <= n; i ++ )
if (fabs(b[i][c]) > fabs(b[t][c]))
t = i;
// 交换 换到最上方
for (int i = c; i <= n + 1; i ++ ) swap(b[t][i], b[r][i]);
// 归一化 从后往前 把这一行全部化成1
for (int i = n + 1; i >= c; i -- ) b[r][i] /= b[r][c];
// 消 用这一行把下面消成0
for (int i = r + 1; i <= n; i ++ )
for (int j = n + 1; j >= c; j -- )
b[i][j] -= b[i][c] * b[r][j];
}
// 转化成对角矩阵
for (int i = n; i > 1; i -- )//列开始
for (int j = i - 1; j; j -- )//行
{
b[j][n + 1] -= b[i][n + 1] * b[j][i];//
b[j][i] = 0;
}
}
//结果是每行的最后一个数
for (int i = 1; i <= n; i ++ ) printf("%.3lf ", b[i][n + 1]);
https://www.acwing.com/activity/content/problem/content/1775/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 15;
int n;
double a[N][N], b[N][N];//a为原先的系数数组 ,b是整理之后的系数 数组
void gauss()
{
// 转化成上三角矩阵
for (int r = 1, c = 1; c <= n; c ++, r ++ )
{
// 找主元
int t = r;
for (int i = r + 1; i <= n; i ++ )
if (fabs(b[i][c]) > fabs(b[t][c]))
t = i;
// 交换
for (int i = c; i <= n + 1; i ++ ) swap(b[t][i], b[r][i]);
// 归一化
for (int i = n + 1; i >= c; i -- ) b[r][i] /= b[r][c];
// 消
for (int i = r + 1; i <= n; i ++ )
for (int j = n + 1; j >= c; j -- )
b[i][j] -= b[i][c] * b[r][j];
}
// 转化成对角矩阵
for (int i = n; i > 1; i -- )
for (int j = i - 1; j; j -- )
{
b[j][n + 1] -= b[i][n + 1] * b[j][i];
b[j][i] = 0;
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n + 1; i ++ )
for (int j = 1; j <= n; j ++ )
scanf("%lf", &a[i][j]);
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= n; j ++ )
{
b[i][j] += 2 * (a[i][j] - a[0][j]);
b[i][n + 1] += a[i][j] * a[i][j] - a[0][j] * a[0][j];
}
gauss();
for (int i = 1; i <= n; i ++ ) printf("%.3lf ", b[i][n + 1]);
return 0;
}
异或版
int gauss()
{
int r, c;
for (r = 1, c = 1; c <= n; c ++ )
{
// 找主元
int t = r;
for (int i = r + 1; i <= n; i ++ )
if (a[i][c])
t = i;
if (!a[t][c]) continue;
// 交换
for (int i = c; i <= n + 1; i ++ ) swap(a[t][i], a[r][i]);
// 消
for (int i = r + 1; i <= n; i ++ )
for (int j = n + 1; j >= c; j -- )
a[i][j] ^= a[i][c] & a[r][j];
r ++ ;
}
int res = 1;
if (r < n + 1)//有解应该是n+1 没有解的话就是无解 有自由元
{
for (int i = r; i <= n; i ++ )
{
if (a[i][n + 1]) return -1; // 出现了 0 == !0,无解
res *= 2;//每个自由元说明多了两种选择
}
}
return res;
}
标签:转化成,int,矩阵,gauss,--,include,高斯消 来源: https://www.cnblogs.com/liang302/p/16683230.html