The Gaussian elimination is to connect the equation Group. (Can be associated with a matrix)
#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <cmath>usingnamespace Std;Const intMAXN =1e2+5;intEquvar;/// equ var variable of equationintA[MAXN][MAXN];/// augmented matrixintX[MAXN]; The number of solutionsBOOLFREE_X[MAXN];/// judge is not free to change the yuanintFree_num;/// number of free argumentsInlineintGCD (intMintN) {if(n = =0)returnMreturnGCD (n, m%n);} InlineintLCM (intAintb) {returnA/GCD (A, b) *b;}intGauss () {intMax_r;/// the existing row with the largest absolute value of the current column //col: processing the current column introw =0;intFree_x_num;intFree_index; for(intCol=0; row<equ&&col<var; row++,col++) {max_r = row; for(inti=row+1; i<equ; i++)if(ABS (A[i][col]) > abs (A[MAX_R][COL)) Max_r = i;if(Max_r! = row) for(intI=0; i<var+1; i++) Swap (A[row][i], a[max_r][i]);if(A[row][col] = =0) {row--;Continue; } for(inti=row+1; i<equ; i++) {if(A[i][col]) {intLCM = LCM (ABS (A[i][col]), ABS (A[row][col));intTp1=lcm/abs (A[i][col]), Tp2=lcm/abs (A[row][col]);if(A[row][col]*a[i][col] <0) TP2 =-TP2; for(intJ=col; j<var+1; J + +) A[i][j] = Tp1*a[i][j]-tp2*a[row][j]; } } } for(intI=row; i<equ; i++)if(a[i][var])return-1;// no solution if(Row <var) { for(inti=row-1; i>=0; i--) {Free_x_num =0; for(intj=0; j<var; J + +)if(A[i][j] && free_x[j]) {free_x_num++; Free_index = j; }if(Free_x_num >1)Continue;intTMP = a[i][var]; for(intj=0; j<var; J + +)if(A[i][j] && j!=free_index) tmp-= a[i][j]*x[j]; X[free_index] = Tmp/a[i][free_index];/// Find out the variable.Free_x[free_index] =0;/// the variable is deterministic.}return var-row;/// number of free arguments} for(intI=var-1; i>=0; i--) {intTMP = a[i][var]; for(intj=i+1; j<var; J + +)if(A[i][j]) tmp-= a[i][j]*x[j];if(Tmp%a[i][i])return-2;/// Description There is a floating-point solution, but no integer solution.X[i] = Tmp/a[i][i]; }return 0;/// Unique Solution}intMain () { while(cin>>equ>>var) { for(intI=0; i<equ; i++) { for(intj=0; j<var+1; J + +) cin>>a[i][j]; } cout<<gauss () <<endl; }return 0;}
Gaussian elimination element Integer elimination template