网上找的模版实在是用不惯。。无奈自己写了一个。。。
下面是系数矩阵n*n,增广矩阵n*(n+1)。
最后结果为 z[i]= y[i]/x[i] ,即 x[i] * z[i] =y[i] .矩阵如下
x1 z1 y1 x1 z1 y1
x2 * z2 = y2 或 0 * z2 = 0
x3 z3 = y3 x3 z3 y3
向量z为解向量。
无解时返回0,有解返回1。复杂度n^3。
int n; ll a[maxn][maxn],x[maxn],y[maxn]; ll lcm(ll a,ll b) { return a/__gcd(a,b)*b; } void debug(int n) { REP(i,1,n){ REP(j,1,n+1) cout<<a[i][j]<<" ";cout<<endl; } cout<<endl; } int Gauss(int n) { REP(i,1,n){ int st=i; while(st<=n&&!a[st][i]) st++; if(st==n+1) continue; REP(j,1,n+1) swap(a[i][j],a[st][j]); ll LCM=1; REP(j,1,n) if(a[j][i]) LCM=lcm(LCM,a[j][i]); REP(j,1,n) REP(k,1,n+1) if(k!=i&&a[j][i]) a[j][k]*=LCM/a[j][i]; REP(j,1,n) if(a[j][i]) a[j][i]=LCM; REP(j,1,n){ if(j==i||!a[j][i]) continue; REP(k,1,n+1) a[j][k]-=a[i][k]; } ll GCD=1; REP(j,1,n+1) if(a[i][j]) GCD=a[i][j]; REP(j,1,n+1) if(a[i][j]) GCD=__gcd(GCD,a[i][j]); REP(j,1,n+1) a[i][j]/=GCD; } REP(i,1,n){ ll GCD=1; REP(j,1,n+1) if(a[i][j]) GCD=a[i][j]; REP(j,1,n+1) if(a[i][j]) GCD=__gcd(GCD,(ll)a[i][j]); REP(j,1,n+1) a[i][j]/=GCD; } REP(i,1,n){ int L=0,R=0; REP(j,1,n) if(a[i][j]) L=1; if(a[i][n+1]) R=1; if(L==0&&R==1) return 0; } REP(i,1,n) x[i]=a[i][i],y[i]=a[i][n+1]; return 1; }