一句话题意:给定n个n元一次方程组,求出它的解。
方程组给定方法:
n
以下n行
每行n+1个数
表示:
A1,1X1+A1,2X2...A1,nXn=A1,n+1
A2,1X1+A2,2X2...A2,nXn=A2,n+1
...
An,1X1+An,2X2...An,nXn=An,n+1
举个栗子例子:
x+2y+3z=3
2x+3y+z=4
3x+y+2z=5
那么就输入:
3 //三元
1 2 3 3
2 3 1 4
3 1 2 5 //就是方程每个字母的系数
输出:
1.33
0.33
0.33 //分别表示x,y,z的值
那么。
怎么做呢?
显然加减消元大法(还有代入)。
直接
x+2y+3z=3(I)
2x+3y+z=4(II)
3x+y+2z=5(III)
I∗2−II:y+5z=2(IV)
I∗3−III:5y+7z=4(V)
5∗IV−V18:z=13(VI)
VI−>IV:y=13(VII)
VI−>I:x+2y=x+2y=2(VIII)
VII−>VIII:x=43
于是就愉快的求出了方程的解了。
于是模拟。
注意代码写得漂亮点。
/*
ID:hh826532
PROB:
LANG:C++
*/
#define _FILE_ ""
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<queue>
#include<time.h>
#include<fstream>
#include<string>
#include<set>
#include<list>
#include<stdlib.h>
#define fr(i,a,b) for(int i=a,_end_=b;i<=_end_;i++)
#define fd(i,a,b) for(int i=a,_end_=b;i>=_end_;i--)
#define frei(s) freopen(s,"r",stdin)
#define freo(s) freopen(s,"w",stdout)
#define ll long long
#define uns unsigned
using namespace std;
#define rt return
#define inf 0x3f3f3f3f
#define infll 4557430888798830399ll
#define pc(x) putchar(x)
#define spc putchar(' ')
#define mem(x,y) memset(x,y,sizeof(x))
#define memm(x,y,z) memset(x,y,sizeof(x[0])*z)
#define gc getchar()
#define ln pc('\n')
#define writeint(x) printf("%d",x)
ll lowbit(ll x)
{
rt x&(-x);
}
int readuint(){
int s=0;
char c=getchar();
while(c<'0'||c>'9')c=gc;
while(c>=48&&c<='9'){
s=s*10+c-48;
c=gc;
}
rt s;
}
int readint(){
int s=0,k=1;
char c=getchar();
while((c<'0'||c>'9')&&c!='-')c=gc;
if(c=='-'){
k=-1;
c=gc;
}
while(c>=48&&c<='9'){
s=s*10+c-48;
c=gc;
}
rt s*k;
}
void OPENFILE(){
char FILENAME[50];
if(strlen(_FILE_)==0)rt;
sprintf(FILENAME,"%s.in",_FILE_);
frei(FILENAME);
sprintf(FILENAME,"%s.out",_FILE_);
freo(FILENAME);
}
int exgcd(int a,int b,int &x,int &y)
{
if(b==0)
{
x=1;
y=0;
return a;
}
int d=exgcd(b,a%b,x,y);
int temp=x;
x=y;
y=temp-a/b*y;
return d;
}
double log(double x,double y)
{
rt log10(x)/log10(y);
}
ll gcd(ll x,ll y)
{
rt y?gcd(y,x%y):x;
}
ll P(ll x,ll y)//x>=y
{
ll r=1;
fr(i,1,y)
r*=(x-i+1);
rt r;
}
ll P(ll x,ll y,ll modnum)//x>=y
{
ll r=1;
fr(i,1,y)
r=r*(x-i+1)%modnum;
rt r;
}
double a[110][110],d;
int n,k;
#define eps 1e-8
bool Gauss()
{
fr(i,1,n)
{
k=i;
fr(j,i+1,n)
if(fabs(a[j][i])>fabs(a[k][i]))
k=j;
d=a[k][i];
if(fabs(d)<eps)
rt 1;
fr(j,i,n+1)
swap(a[i][j],a[k][j]);
fr(j,i,n+1)
a[i][j]/=d;
fr(_,1,n)
if(_!=i)
{
d=a[_][i];
fr(j,i,n+1)
a[_][j]-=a[i][j]*d;
}
}
rt 0;
}
int main(){
OPENFILE();
n=readuint();
fr(i,1,n)
fr(j,1,n+1)
scanf("%lf",&a[i][j]);
if(Gauss())
puts("No Solution");
else
fr(i,1,n)
printf("%.2lf\n",a[i][n+1]);
rt 0;
}
这样就完美解决啦!
福利第一弹:
download
没学过OI的都会的Gauss解方程程序