题目链接:点击打开链接
求行列式的值,自己写了个板子,精度的地方有点蛋疼然后就用了很麻烦的方式.额,,,
比较实用的.
行列式两行交换结果是要*-1的.
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
#define maxn 33
#define eps 1e-10
int n;
double a[maxn][maxn];
long long solve () {
double ans = 1.0;
int i, j, k, col, max_r;
for (k = 0, col = 0; k < n && col < n; k++, col++) {//转化成上三角矩阵
max_r = k;
for (int i = k+1; i < n; i++) { //找到最大的绝对值数所在的行
if (fabs (a[i][col]) > fabs (a[max_r][col]))
max_r = i;
}
if (k != max_r) { //交换行
for (int j = col; j < n; j++) {
swap (a[k][j], a[max_r][j]);
}
ans *= (-1);//行列式换行改变符号
}
for (int i = k+1; i < n; i++) { //消去
if (a[i][col]) {
double tmp = -a[i][col]/a[k][col];
for (int j = col; j < n; j++) {
a[i][j] += tmp*a[k][j];
}
}
}
}
for (i = 0; i < n; i++) ans *= a[i][i];
long long p1 = ceil (ans), p2 = floor (ans);
if (ans-p2 < p1-ans)
return p2;
else
return p1;
}
int main () {
//freopen ("in.txt", "r", stdin);
while (1) {
cin >> n;
if (n == 0) {
cout << "*" << "\n";
break;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cin >> a[i][j];
}
cout << solve () << "\n";
}
return 0;
}
另外扒了一份矩阵辗转相除的板子,可以避免精度误差.
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define maxn 33
#define eps 1e-10
long long a[maxn][maxn];
int n;
long long det () //按列化为下三角
{
long long res = 1;
for(int i = 0; i < n; ++i)
{
if (!a[i][i])
{
bool flag = false;
for (int j = i + 1; j < n; ++j)
{
if (a[j][i])
{
flag = true;
for (int k = i; k < n; ++k)
{
swap (a[i][k], a[j][k]);
}
res = -res;
break;
}
}
if (!flag)
{
return 0;
}
}
for (int j = i + 1; j < n; ++j)
{
while (a[j][i])
{
long long t = a[i][i] / a[j][i];
for (int k = i; k < n; ++k)
{
a[i][k] = a[i][k] - t * a[j][k];
swap (a[i][k], a[j][k]);
}
res = -res;
}
}
res *= a[i][i];
}
return res;
}
int main()
{
//freopen("in.txt", "r", stdin);
while (1) {
cin >> n;
if (n == 0) {
cout << "*\n";
break;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cin >> a[i][j];
}
cout << det () << "\n";
}
return 0;
}