计算方法 - 列主元消元法(线性方程组的解法)

计算方法 - 列主元消元法(线性方程组的解法)_第1张图片
列主元消元法比起高斯消元增加了每次化简时取第一列最大元素作为主元
即:
计算方法 - 列主元消元法(线性方程组的解法)_第2张图片
题目:
计算方法 - 列主元消元法(线性方程组的解法)_第3张图片
代码:

#include 
#include 
#include 
#include 
#include 
using namespace std;
#define ll long long
const int maxn = 205;
const int INF = 0x3f3f3f;

void _pri(double x, long long n, bool f) { //预处理数字,保留位数,是否需要四舍五入
    double _ma = 1.0, _mi = 1.0, _t = 10.0;
    long long _n = n, i = 0, cnt = 0;
    while(_n) {
        if(_n % 2 == 1) _ma *= _t, _mi /= _t;
        _n >>= 1, _t *= _t;
    }
    if(x < 0) printf("-"), x = -x;
    if(x < 1) printf("0.");
    if(x < _mi) {
        for(i = 0; i < n; ++i) printf("0");
        return;
    }
    double t = 1.0, _x = x;
    if(x >= 1)
        while(_x >= 1)
            _x /= 10, cnt++;
    if(x < 1)
        while(_x < 1) {
            if(_x < 0.1) printf("0");
            _x *= 10;
        }
    while(_x < _ma) _x *= 10;
    long long a = (long long)_x;
    if(f == 1 && cnt <= n && a % 10 >= 5)
        if(a > 0) a += 10;
        else if(a < 0) a -= 10;
    a /= 10;
    char ans[105]; _n = 0;
    while(a) {
        ans[_n++] = a%10 + '0';
        a /= 10;
    }
    for(i = 0; i < _n; ++i) {
        if(i == cnt && cnt != 0) printf(".");
        printf("%c",ans[_n - i - 1]);
    }
}

double a[1005 * 1005] = {0.0}, b[1005] = {0.0};
double x[1005] = {0.0};
int n = 0, n2 = 0;

inline void IN() { //输入
    int t = 0;
    while(scanf("%lf",&a[++t]) != EOF) {}
    while(n*(n+1) != (t-1)) {n++;}
    n2 = n * n;
}

inline double *A(int i, int j) {
    return &a[j + (i-1) * n];
}

inline double *B(int j) {
    return &a[j + n2];
}

void _swap(int a, int b) {
    for(int i = 1; i <= n; ++i) {
        swap(*A(a,i), *A(b,i));
    }
    swap(*B(a), *B(b));
}

inline void SIM() { //化简为三角行列式
    for(int k =  1; k <= n; ++k) {
        double ma = abs(*A(k,k)), _i = k;
        for(int i = k+1; i <= n; ++i) {
            if(abs(*A(i,k)) > ma) {
                ma = abs(*A(i,k));
                _i = i;
            }
        }
        _swap(_i,k);
        for(int i = k+1; i <= n; ++i) {
            double mik = *A(i,k) / *A(k,k);
            for(int j = k; j <= n; ++j) {
                *A(i,j) -= *A(k,j) * mik;
            }
            *B(i) -= mik * *B(k);
        }
    }
}

inline void _Pri(){
    for(int i = 1; i <= n; ++i) {
        for(int j = 1; j <= n; ++j) {
            printf("%lf ", *A(i,j));
        }
        printf("\n");
    }
    for(int i = 1; i <= n; ++i) {
        printf("%lf ", *B(i));
    }
    printf("\n");
}

inline void ANS() { //迭代求解
    for(int i = n; i >= 1; --i) {
        x[i] = *B(i);
        for(int j = i+1; j <= n; ++j) {
            x[i] -= *A(i,j) * x[j];
        }
        x[i] /= *A(i,i);
    }
}

inline void OUT() {
    for(int i = 1; i <= n; ++i) {
        _pri(x[i],(long long)5,1); printf("\n\n");
    }
}

int main() {
    IN();
    SIM();
    ANS();
    OUT();
    return 0;
}

你可能感兴趣的:(计算方法)