题解:P2455 [SDOI2006] 线性方程组
Unknown_Accepted · · 题解
:::info[一些闲话] 这道题怎么能没有线性基题解呢?题解区居然全是高斯消元,没有一个讲的是线性基!? ::: 线性基的作用远不止异或最大值,实际上可以解方程,不要求齐次。
首先,我们对于每一个方程:
我们构造一个向量(这里用行向量):
然后我们先在不考虑
一下就能解出
这里
接下来看看怎么判断无解。
众所周知,线性基构造过程要用其他行对新加入的行消元,如果我们消到最后发现新加入的行别的项都是
如果此时
然后再看看有无数解的情况。
如果我们在迭代求解过程中,发现某行所有数都是
当然我们不需要真的枚举所有元素判断,根据线性基的性质,如果第
#include<bits/stdc++.h>
using namespace std;
const int N=55;
struct func{
double a[N];
int n;
double& operator[](int i){
return a[i];
}
const double& operator[](int i)const{
return a[i];
}
func operator*(double k)const{
func res;
res.n=n;
for(int i=1;i<=n;i++){
res[i]=a[i]*k;
}
return res;
}
func operator+(const func& b)const{
func res;
res.n=n;
for(int i=1;i<=n;i++){
res[i]=a[i]+b[i];
}
return res;
}
func operator-(const func& b)const{
func res;
res.n=n;
for(int i=1;i<=n;i++){
res[i]=a[i]-b[i];
}
return res;
}
};
func operator*(double k,const func& a){
return k*a;
}
int n;
func b[N];
const double eps=1e-9;
bool is0(double x){
return fabs(x)<=eps;
}
unordered_map<int,double> sol;
int main(){
cin>>n;
for(int i=1;i<=n;i++){
func a;a.n=n+1;
for(int j=1;j<=n+1;j++){
cin>>a[j];
}
for(int j=1;j<=n;j++){
if(!is0(a[j])){
if(!is0(b[j][j])){
a=a-b[j]*(a[j]/b[j][j]);
}else{
b[j]=a;
break;
}
}
}
bool az=1;
for(int j=1;j<=n;j++){
if(!is0(a[j]))az=0;
}
if(az){
if(!is0(a[n+1])){
cout<<-1;return 0;
}
}
}
for(int i=n;i>=1;i--){
double sm=0;
if(is0(b[i][i])){
cout<<0;
return 0;
}
for(int j=i+1;j<=n;j++){
sm+=b[i][j]*sol[j];
}
sol[i]=(b[i][n+1]-sm)/b[i][i];
}
for(int i=1;i<=n;i++){
cout<<'x'<<i<<'='<<sol[i]<<"\n";
}
return 0;
}//专栏志愿者都可爱喵!
:::