跳到正文

学习·文化课

行列式的计算模拟

cqbz_whr约 2 分钟
原文

这是 2026年1月13日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年11月2日
收录
2026年1月13日
更新
2026年11月16日
篇幅
约 2 分钟
获赞
1

版本

  1. v2当前
  2. v1

突然发现行列式的计算很像模拟, 于是…

C++
#include <bits/stdc++.h>
using namespace std;
int n;
int ans = 0;
bool visx[10005];
int a[10005];
int mp[10005][10005];
int check() {
	int sum = 0;
	for(int i = 1; i <= n; i++) {
		for(int j = i + 1; j <= n; j++) {
			if(a[i] > a[j]) {
				sum++;
			}
		}
	}//逆序数的个数
	return sum % 2 == 0;//奇偶确定正负
}
void p(int step) {
    if (step == n + 1) {
    	int l = 1;
        for (int i = 1; i <= n; i++) {
        	cout << a[i] <<" "; 
            l *= mp[i][a[i]];
        }
        cout << endl;
        if(check()) {
        	cout << "+" << l;
        	ans += l;
		}
		else {
			cout << "-" << l;
			ans -= l;
		}
		cout << endl;
        return;
    }
    for (int i = 1; i <= n; i++) {
        if (visx[i])
            continue;
        a[step] = i;
        visx[i] = 1;
        p(step + 1);
        visx[i] = 0;
    }
}
int main() {
    cin >> n;
    for(int i = 1; i <= n; i++) {
    	for(int j = 1; j <= n; j++) {
    		cin >> mp[i][j];
		}
	}
    p(1);
    cout << ans;
}

3

1 1 -2

5 -2 7

2 -5 4

输出

代码
1 3 2
--35
2 1 3
-20
2 3 1
+14
3 1 2
+50
3 2 1
-8
63