Advertisement
istinishat

Gauess Elimination Template

Aug 27th, 2017
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. //Gaussian Elimination Template collected from Anik
  4. /*  how to use:
  5.  
  6. let, we have these eqns to solve
  7.  
  8. 2x+y-z=8
  9. -3x-y+2z=-11
  10. -2x+y+2z=-3
  11.  
  12. put matrix
  13. 2 1 -1 8
  14. -3 -1 2 -11
  15. -2 1 2 -3
  16.  
  17. int Eqns[][] array index i,j starts from 1
  18.  
  19. solution for a variable is stored in sol[]  array,
  20. if no solution for a variable , nosol[] array of corresponding var is true
  21.  
  22. */
  23. #define EPS 1e-8
  24. #define MAX 103
  25.  
  26. double sol[MAX];
  27. int nosol[MAX];
  28. double Eqns[MAX][MAX];
  29.  
  30. void Gauss(int n) {
  31.     int i,j;
  32.     for(i=1;i<=n;i++) {
  33.         int k=i;
  34.         for(j=i+1;j<=n;j++) if(fabs(Eqns[k][i])<fabs(Eqns[j][i])) k=j;
  35.         if(fabs(Eqns[k][i])<EPS) continue;
  36.         if(k!=i) for(j=1;j<=n+1;j++) swap(Eqns[k][j],Eqns[i][j]);
  37.  
  38.         for(j=1;j<=n;j++){
  39.             if(i==j) continue;
  40.             for(k=n+1;k>=i;k--){
  41.                 Eqns[j][k]-=Eqns[j][i]/Eqns[i][i]*Eqns[i][k];
  42.             }
  43.         }
  44.     }
  45.     memset(nosol,0,sizeof(nosol));
  46.     for(i=n;i>=1;i--){
  47.         if(fabs(Eqns[i][n+1])>EPS && fabs(Eqns[i][i])<EPS) nosol[i]=1;
  48.         else{
  49.             if(fabs(Eqns[i][n+1])<EPS) sol[i]=0;
  50.             else sol[i]=Eqns[i][n+1]/Eqns[i][i];
  51.         }
  52.         for(j=i+1;j<=n;j++) if(fabs(Eqns[i][j])>EPS && nosol[j]) nosol[i] = 1;
  53.     }
  54. }
  55.  
  56. int main()
  57. {
  58.     //freopen("input.txt","r",stdin);
  59.     /*
  60.         above example input
  61.     */
  62.     for(int i=1;i<=4;i++){
  63.         for(int j=1;j<=4;j++)
  64.             cin>>Eqns[i][j];
  65.     }
  66.     Gauss(3);
  67.  
  68.     for(int i=1;i<=3;i++){
  69.         if(nosol[i])cout<<"no solution "<<endl;
  70.         else cout<<sol[i]<<endl;
  71.     }
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement