正文
增加 37 行删除 45 行
2 行未改动3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081822 行未改动#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;}```31 1 -25 -2 72 -5 4输出```1 3 2--352 1 3-202 3 1+143 1 2+503 2 1-8632 行未改动345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273742 行未改动#include <bits/stdc++.h>using namespace std;int n;int ans = 0;bool visx[10005]; // 保持你原有的数组大小和命名int a[10005]; // 存储排列:a[i]表示第i行选的列号int mp[10005][10005];// 优化:不再全局计算逆序数,而是递归时传递当前符号(1=正,-1=负)void p(int step, int sign) {if (step == n + 1) {int l = 1;// 输出当前排列(和你原代码一致的调试输出)for(int i = 1; i <= n; i++) {cout << a[i] <<" ";l *= mp[i][a[i]];}cout << endl;// 直接用sign判断符号,无需调用check()if(sign == 1) {cout << "+" << l;ans += l;} else {cout << "-" << l;ans -= l;}cout << endl;return;}for (int i = 1; i <= n; i++) {if (visx[i])continue;// 计算当前选列i时,新增的逆序对数(仅统计已选列中比i大的数)int cnt = 0;for(int j = 1; j < step; j++) { // step之前的行已选列存在a[j]中if(a[j] > i) cnt++;}// 新符号:原符号 * (-1)^cnt(cnt奇则翻转,偶则不变)int new_sign = sign * (cnt % 2 == 0 ? 1 : -1);// 回溯(和你原代码写法完全一致)a[step] = i;visx[i] = 1;p(step + 1, new_sign); // 传递新符号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, 1); // 初始step=1,初始符号为正(1)cout << ans;return 0;}3```1 1 -25 -2 72 -5 4输出1 3 263