模意义下的高斯消元(模板)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#define N 300
using namespace std;
typedef long long ll;
ll n,p,a[N+5][N+5];
void init(){
    cin>>n>>p;
    for (int i = 1;i <= n; ++i)
      for (int j = 1;j <= n+1; ++j)
        cin>>a[i][j];
}

ll pow_mul(ll r,ll b,ll p){
    ll base=r; r=1;
    for (;b;b>>=1){
        if (b&1) r=r*base%p;
        base=base*base%p; 
    }
    return r;
}

ll inv(ll x){ return pow_mul(x,p-2,p);} 

bool gauss(){
    for (int i = 1;i <= n; ++i){
        if (!a[i][i]) { a[i][i]=1; a[i][n+1]=(a[i][n+1]+a[i][i])%p;}
        ll x = inv(a[i][i]); 
        for (int j = i; j <= n+1; ++j) a[i][j]=a[i][j]*x%p;
        for (int j = i+1;j <= n; ++j) 
          {  ll t = a[j][i];
          for (int k = 1;k <= n+1; ++k)
             a[j][k]=((a[j][k]-t*a[i][k])%p+p)%p;}
    } 
    for (int i = n-1; i>=1; --i)
      for (int j = i+1; j <= n; ++j)
        a[i][n+1]=((a[i][n+1]-a[i][j]*a[j][n+1])%p+p)%p;
    return 1; 
}

void print(){
    for (int i = 1; i <= n; ++i) cout<<a[i][n+1]<<endl;
}

int main(){
    init();
    gauss();
    print();
    return 0;
} 

你可能感兴趣的:(模意义下的高斯消元(模板))