部分主元法高斯消元
# include <iostream>
# include <cmath> using namespace std;
const int N = 109 ;
const double eps = 1e-6 ;
double a[ N] [ N] ;
int n;
void init ( )
{ cin >> n; for ( int i = 0 ; i < n; i++ ) for ( int j = 0 ; j < n + 1 ; j++ ) cin >> a[ i] [ j] ;
}
bool Gauss ( )
{ int l = 0 , r = 0 ; for ( l = 0 , r = 0 ; r < n; r++ ) { int tt = l; for ( int i = l; i < n; i++ ) if ( fabs ( a[ tt] [ r] ) < fabs ( a[ i] [ r] ) ) tt = i; if ( fabs ( a[ tt] [ r] ) < eps) continue ; for ( int i = r; i < n + 1 ; i++ ) swap ( a[ tt] [ i] , a[ l] [ i] ) ; for ( int i = n; i >= r; i-- ) a[ l] [ i] /= a[ l] [ r] ; for ( int i = l + 1 ; i < n; i++ ) { if ( fabs ( a[ i] [ r] ) < eps) continue ; for ( int j = n; j >= r; j-- ) a[ i] [ j] -= a[ l] [ j] * a[ i] [ r] ; } l++ ; } for ( int i = n - 1 ; i >= 0 ; i-- ) for ( int j = i + 1 ; j < n; j++ ) a[ i] [ n] -= a[ j] [ n] * a[ i] [ j] ; if ( l == n) return 0 ; return 1 ;
}
int main ( )
{ init ( ) ; if ( ! Gauss ( ) ) for ( int i = 0 ; i < n; i++ ) cout << "x" << i << " = " << a[ i] [ n] << '\n' ; else cout << "无解!!!\n" ;
}
完全主元法高斯消元
# include <bits/stdc++.h>
using namespace std;
# define PII pair< int , int >
const int N = 109 ;
const double eps = 1e-6 ;
double a[ N] [ N] ;
int id[ N] ;
int n; void init ( )
{ cin >> n; for ( int i = 0 ; i < n; i++ ) id[ i] = i; for ( int i = 0 ; i < n; i++ ) for ( int j = 0 ; j < n + 1 ; j++ ) cin >> a[ i] [ j] ;
}
PII Get_Max_Idx ( int l, int r)
{ PII idx; double mx = 0 ; for ( int i = l; i < n; i++ ) for ( int j = r; j < n; j++ ) if ( fabs ( a[ i] [ j] ) > mx) mx = fabs ( a[ i] [ j] ) , idx = { i, j} ; return idx;
}
bool Gauss ( )
{ int l = 0 , r = 0 ; for ( l = 0 , r = 0 ; r < n; r++ ) { PII tt = Get_Max_Idx ( l, l) ; for ( int i = r; i < n + 1 ; i++ ) swap ( a[ tt. first] [ i] , a[ l] [ i] ) ; tt. first = l; for ( int i = 0 ; i < n; i++ ) swap ( a[ i] [ tt. second] , a[ i] [ r] ) ; swap ( id[ tt. second] , id[ r] ) ; for ( int i = n; i >= r; i-- ) a[ l] [ i] /= a[ l] [ r] ; for ( int i = l + 1 ; i < n; i++ ) { if ( fabs ( a[ i] [ r] ) < eps) continue ; for ( int j = n; j >= r; j-- ) a[ i] [ j] -= a[ l] [ j] * a[ i] [ r] ; } l++ ; } for ( int i = n - 1 ; i >= 0 ; i-- ) for ( int j = i + 1 ; j < n; j++ ) a[ i] [ n] -= a[ j] [ n] * a[ i] [ j] ; if ( l == n) return 0 ; return 1 ;
}
int main ( )
{ init ( ) ; if ( ! Gauss ( ) ) { for ( int i = 0 ; i < n; i++ ) cout << "x" << id[ i] << " = " << a[ i] [ n] << '\n' ; } else cout << "无解!!!\n" ;
}