SPOJ - DETER3 - Find The Determinant III - 矩阵行列式的值取模 - 模是任意数
传送门
按理说,在求行列式时,化简成上三角新式,需要除以数字,如果要除以mod,那么肯定会产生逆元
而对于逆元的处理,这里肯定需要保证模是质数。
但对于模是任意数时
不是特别懂,好像是类似gcd的辗转相除法求的
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 210;
ll mod;
ll C[MAX_N][MAX_N];
ll det(ll mat[][MAX_N], int n){
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= n; ++j) {
mat[i][j] = (mat[i][j] % mod + mod) % mod;
}
}
ll res = 1;
int cnt = 0;
for(int i = 1; i <= n; ++i) {
for(int j = i + 1; j <= n; ++j) {
while(mat[j][i]) {
ll t = mat[i][i] / mat[j][i];
for(int k = i; k <= n; ++k) {
mat[i][k] = (mat[i][k] - mat[j][k] * t % mod) % mod;
// cout << mat[i][k] << endl;
swap(mat[i][k], mat[j][k]);
}
cnt++;
}
}
if(mat[i][i] == 0) return 0;
res = res * mat[i][i] % mod;
}
if(cnt & 1) res = -res;
return (res + mod) % mod;
}
int main(){
int n;
while(~scanf("%d%lld", &n, &mod)){
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= n; ++j) {
scanf("%lld", &C[i][j]);
}
}
printf("%lld\n", det(C, n));
}
return 0;
}
I‘m Stein, welcome to my blog