题目描述
给你一个 N N 元一次方程组,求解其解。如果方程组无实数解输出-1;如果有无穷多实数解,输出0;如果有唯一解,则输出解(小数点后保留两位小数)。
数据范围
#include <bits/stdc++.h>
#define rep( i , l , r ) for( int i = (l) ; i <= (r) ; ++i )
#define per( i , r , l ) for( int i = (r) ; i >= (l) ; --i )
#define erep( i , u ) for( int i = head[(u)] ; ~i ; i = e[i].nxt )
using namespace std;
int _read(){
char ch = getchar();
int x = 0 , f = 1 ;
while( !isdigit( ch ) )
if( ch == '-' ) f = -1 , ch = getchar();
else ch = getchar();
while( isdigit( ch ) )
x = (ch - '0') + x * 10 , ch = getchar();
return x * f;
}
const int maxn = 50 + 5;
int N ;
double x[maxn] , a[maxn][maxn];
int Guass(){
int max_r = 0 , col = 1 , k; // col 表示当前的处理的列
for( k = 1 ; k <= N && col <= N ; ++k , ++col ){
max_r = k;
rep( i , k + 1 , N )
if( abs(a[i][col]) > abs(a[max_r][col]) ) max_r = i;
if( max_r != k ) rep( j , 1 , N + 1 ) swap( a[max_r][j] , a[k][j] );
if( 0 == a[k][col] ) { --k ; continue; }
int t1 , t2;
rep( i , k + 1 , N ){
if( a[i][col] == 0 ) continue;
double mul = -a[i][col] / a[k][col];
rep( j , k , N + 1 )
a[i][j] += a[k][j] * mul;
}
}
rep( i , k , N ) if( a[i][col] != 0 ) return -1;
if( k <= N ) return 0;
per( i , N , 1 ){
double t = a[i][N + 1];
rep( j , i + 1 , N ){
if( a[i][j] ) t -= a[i][j] * x[j];
}
x[i] = t / a[i][i];
}
return 1;
}
int main(){
scanf("%d" , &N);
rep( i , 1 , N )
rep( j , 1 , N + 1 )
scanf("%lf", &a[i][j]);
int flg = Guass();
if( flg == -1 ) puts("-1");
else if( flg == 0 ) puts("0");
else{
rep( i , 1 , N )
printf("x%d=%.2lf\n" , i , x[i] );
}
return 0;
}