模板题:洛谷P3389
高斯消元法
Code:
int n;
double a[MX][MX];
double ans[MX];
void gauss(){
for(int i = 1;i <= n;++i){
int r = i;
for(int j = i + 1;j <= n;++j){
if(fabs(a[r][i]) < fabs(a[j][i])) r = j;
}
if(fabs(a[r][i]) < eps){
printf("No Solution\n");return ;
}
if(i != r) swap(a[i],a[r]);
double div = a[i][i];
for(int j = i;j <= n + 1;++j){
a[i][j] /= div;
}
for(int j = i + 1;j <= n;++j){
div = a[j][i];
for(int k = i;k <= n + 1;++k){
a[j][k] -= a[i][k] * div;
}
}
}
ans[n] = a[n][n+1];//回代
for(int i = n - 1;i >= 1;--i){
ans[i] = a[i][n+1];
for(int j = i + 1;j <= n;++j)
ans[i] -= (a[i][j] * ans[j]);
}
for(int i = 1;i <= n;++i) printf("%.2f\n", ans[i]);
}
int main(){
scanf("%d",&n);
for(int i = 1;i <= n;++i){
for(int j = 1;j <= n+1;++j){
scanf("%lf",&a[i][j]);
}
}
gauss();
return 0;
}
高斯-约旦消元法
Code:
int n;
double a[MX][MX];
void gauss(){
for(int i = 1;i <= n;++i){
int max = i;
for(int j = i + 1;j <= n;++j){
if(fabs(a[j][i]) < fabs(a[max][i])) max = j;
}
swap(a[i],a[max]);
if(!a[i][i]) {printf("No Solution\n"); return ;}
for(int j = 1;j <= n;++j){
if(j != i){
double div = a[j][i] / a[i][i];
for(int k = i + 1;k <= n + 1;++k){
a[j][k] -= a[i][k] * div;
}
}
}
}
for(int i = 1;i <= n;++i){
printf("%.2f\n", a[i][n+1] / a[i][i]);
}
// for(int i = 1;i <= n;++i){
// for(int j = 1;j <= n + 1;++j){
// printf("%8.2f ", a[i][j]);
// }
// printf("\n");
// }
}
int main(){
scanf("%d",&n);
for(int i = 1;i <= n;++i){
for(int j = 1;j <= n+1;++j){
scanf("%lf",&a[i][j]);
}
}
gauss();
return 0;
}