题面
https://www.luogu.org/problem/P2455
题解
#include<iostream> #include<iomanip> #include<cmath> #include<cstdio> #define eps 1e-5 using namespace std; int n,i,j,k,x,p; double a[105][105],ta[105][105],ans[105],t,Max,sum; bool book[105]; bool check(){ int i,j,k; for (i=1;i<=n;i++) { bool s=0; for (j=1;j<=n+1;j++) if (ta[i][j]!=0) s=1; if (!s) return 1; } for (i=1;i<=n;i++) for (j=i+1;j<=n;j++) { bool s=0; double x=ta[i][1]/ta[j][1]; for (k=1;k<=n+1;k++) if (ta[i][k]/ta[j][k]!=x) s=1; if (!s) return 1; } return 0; } int main(){ cin>>n; bool yichang=0; for (i=1;i<=n;i++) for (j=1;j<=n+1;j++) {cin>>a[i][j]; ta[i][j]=a[i][j]=a[i][j]*1.0;} for (x=1;x<=n;x++){ Max=0; for (j=x;j<=n;j++) if (fabs(a[j][x])>Max){Max=a[j][x];p=j;} for (j=x;j<=n+1;j++){t=a[x][j];a[x][j]=a[p][j];a[p][j]=t;} for (j=x+1;j<=n+1;j++) { if(fabs(a[x][x])<eps) {ans[x]=2.3333; book[x]=1; yichang=1; goto L1;} else a[x][j]=(a[x][j]*1.0)/(a[x][x]*1.0); } a[x][x]=1; for (j=x+1;j<=n;j++){ t=a[j][x]; for (k=x;k<=n+1;k++) a[j][k]=a[j][k]-t*a[x][k]; a[j][x]=0; } L1:; } if (a[n][n]==0) { yichang=1; ans[n]=2.333; } else { ans[n]=a[n][n+1]; } for (i=n-1;i>=1;i--) if (!book[i]) { sum=0; for (j=i+1;j<=n;j++) sum=sum+a[i][j]*ans[j]; ans[i]=(a[i][n+1]-sum)/a[i][i]; } bool can=1; for (i=1;i<=n;i++) { double ansx=0; for (j=1;j<=n;j++) ansx+=(ans[j]*ta[i][j]); if (fabs(ansx-ta[i][n+1])>eps) can=0; } if (yichang) { if (can) printf("0"); else printf("-1"); return 0; } if (check()) { puts("0"); return 0; } for (i=1;i<=n;i++) { printf("x%d=",i); if (fabs(ans[i])<eps) ans[i]=0.0; printf("%.2lf ",ans[i]); } }