(矩阵行列式求模)Find The Determinant III

https://www.spoj.com/problems/DETER3/en/

题意即为输出矩阵的行列式求模的答案
分类讨论模为不为质数的情况即可,若为质数,可以使用费马小定理;否则利用公式a/b%m=(a%(b*m))/b

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;

const int maxn = 200 + 3;
ll a[maxn][maxn], p;
int isprime;
ll qpow(ll a, ll b) {
    ll ret = 1;
    while(b) {
        if(b & 1) ret = ret * a % p;
        b >>= 1;
        a = a * a % p;
    }
    return ret;
}
ll Dot_is_prime(int n) {
    ll ret = 1;
    int flg = 0;
    for(int i = 1; i <= n; ++i) {
        for(int j = i + 1; j <= n; ++j) {
            while(a[j][i]) {
                ll t = a[i][i] * qpow(a[j][i], p - 2) % p;
                for(int k = 1; k <= n; ++k) 
                    a[i][k] = (a[i][k] - a[j][k] * t % p + p) % p;
                for(int k = 1; k <= n; ++k)
                    swap(a[i][k], a[j][k]);
                ++flg;
            }
        }
        if(a[i][i] == 0) return 0;
        ret = ret * a[i][i] % p;
    }
    if(flg & 1) ret = -ret, ret %= p, ret = (ret + p) % p;
    return ret;
}
// (a/b)%m = (a % (b*m))/b
ll Dot_is_not_prime(int n) {
    ll ret = 1;
    int flg = 0;
    for(int i = 1; i <= n; ++i) {
        for(int j = i + 1; j <= n; ++j) {
            while(a[j][i]) {
                ll t = (a[i][i] % (a[j][i] * p)) / a[j][i];
                for(int k = 1; k <= n; ++k) 
                    a[i][k] = (a[i][k] - a[j][k] * t % p + p) % p;
                for(int k = 1; k <= n; ++k)
                    swap(a[i][k], a[j][k]);
                ++flg;
            }
        }
        if(a[i][i] == 0) return 0;
        ret = ret * a[i][i] % p;
    }
    if(flg & 1) ret = -ret, ret %= p, ret = (ret + p) % p;
    return ret;
}
bool Prime(ll p) {
    for(int i = 2; i * i <= p; ++i) 
        if(p % i == 0) return false;
    return true;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    while(cin >> n >> p) {
        isprime = Prime(p);
        for(int i = 1; i <= n; ++i) {
            for(int j = 1; j <= n; ++j) {
                cin >> a[i][j];
                a[i][j] %= p;
                a[i][j] = (a[i][j] + p) % p;
            }
        }
        if(isprime) cout << Dot_is_prime(n) << endl;
        else cout << Dot_is_not_prime(n) << endl;
    }
}

你可能感兴趣的:(总结)