Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- //Gaussian Elimination Template collected from Anik
- /* how to use:
- let, we have these eqns to solve
- 2x+y-z=8
- -3x-y+2z=-11
- -2x+y+2z=-3
- put matrix
- 2 1 -1 8
- -3 -1 2 -11
- -2 1 2 -3
- int Eqns[][] array index i,j starts from 1
- solution for a variable is stored in sol[] array,
- if no solution for a variable , nosol[] array of corresponding var is true
- */
- #define EPS 1e-8
- #define MAX 103
- double sol[MAX];
- int nosol[MAX];
- double Eqns[MAX][MAX];
- void Gauss(int n) {
- int i,j;
- for(i=1;i<=n;i++) {
- int k=i;
- for(j=i+1;j<=n;j++) if(fabs(Eqns[k][i])<fabs(Eqns[j][i])) k=j;
- if(fabs(Eqns[k][i])<EPS) continue;
- if(k!=i) for(j=1;j<=n+1;j++) swap(Eqns[k][j],Eqns[i][j]);
- for(j=1;j<=n;j++){
- if(i==j) continue;
- for(k=n+1;k>=i;k--){
- Eqns[j][k]-=Eqns[j][i]/Eqns[i][i]*Eqns[i][k];
- }
- }
- }
- memset(nosol,0,sizeof(nosol));
- for(i=n;i>=1;i--){
- if(fabs(Eqns[i][n+1])>EPS && fabs(Eqns[i][i])<EPS) nosol[i]=1;
- else{
- if(fabs(Eqns[i][n+1])<EPS) sol[i]=0;
- else sol[i]=Eqns[i][n+1]/Eqns[i][i];
- }
- for(j=i+1;j<=n;j++) if(fabs(Eqns[i][j])>EPS && nosol[j]) nosol[i] = 1;
- }
- }
- int main()
- {
- //freopen("input.txt","r",stdin);
- /*
- above example input
- */
- for(int i=1;i<=4;i++){
- for(int j=1;j<=4;j++)
- cin>>Eqns[i][j];
- }
- Gauss(3);
- for(int i=1;i<=3;i++){
- if(nosol[i])cout<<"no solution "<<endl;
- else cout<<sol[i]<<endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement