【高斯消元】整数高斯消元模板

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXN = 100;
int mabs(int u){return u>0?u:-u;}
int gcd(int a,int b){
    int c;
    while(b){
        c = a;
        a = b;
        b = c%b;
    }
    return a;
}
struct Matrix{
    int Ma[MAXN+10][MAXN+11];
    int Ans[MAXN+10];
    int n;
    void solve(){
        int m = n+1, k=1;
        for(int i=1;i<=n;i++, k++){
            int Maxp = i;
            for(int j=i+1;j<=n;j++)
                if(mabs(Ma[j][k]) > mabs(Ma[Maxp][k]))
                    Maxp = j;
            if(Maxp != i)
                swap(Ma[Maxp], Ma[i]);
            for(int j=i+1;j<=n;j++){
                if(Ma[j][k] != 0){
                    int lcm = Ma[j][k] * Ma[i][k] / gcd(Ma[j][k], Ma[i][k]);
                    int bl = lcm / Ma[j][k], bl2 = lcm / Ma[i][k];
                    for(int p=1;p<=m;p++)
                        Ma[j][p] = Ma[j][p] * bl - Ma[i][p] * bl2;
                }
            }
        }
        for(int i=n;i>=1;i--){
            for(k=n;k>i;k--)
                Ma[i][m] -= Ma[i][k] * Ans[k];
            Ans[i] = Ma[i][m] / Ma[i][i];
        }
    }
}M, Ym;
int main(){
    int n, m;
    scanf("%d%d", &n, &m);
    M.n = n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            scanf("%d", &M.Ma[i][j]);
        }
    }
    M.solve();
    for(int i=1;i<=n;i++)
        printf("%d\n", M.Ans[i]);

    return 0;
}
/*
3 4
2 -1 3 1
4 2 5 4
2 0 2 6
*/

posted on 2016-01-28 11:28  JeremyGuo  阅读(210)  评论(0编辑  收藏  举报

导航