大家好,又见面了,我是你们的朋友全栈君。
permutation.h
/***********************************/
/*
Nonstandard Permutation header
Copyright (C) 2021---@情久小羊,#Free
There is no data error check
*/
/***********************************/
#pragma once
#include<initializer_list>
#include <xutility>
#include <xstring>
#include<vector>
#include <stdexcept>
using std::vector;
using std::initializer_list;
class Permutation {
int rank;//n阶行列式
vector<vector<int>>data;
public:
Permutation(int rank, vector<vector<int>> data) {
if (data.size() != rank)throw std::range_error("行列式大小异常");
for (int i = 0; i < data.size(); ++i) {
if (data.at(i).size() != rank)throw std::range_error("行列式大小异常");
}
this->data = data;
this->rank = rank;
}
Permutation(int rank, initializer_list<int>data_list) {
if (data_list.size() != rank * rank)throw std::range_error("行列式大小异常");
vector<int>v;
for (auto i = data_list.begin(); i != data_list.end(); ++i) {
v.push_back(*i);
if (v.size() == rank) {
this->data.push_back(v);
v.clear();
}
}
this->rank = rank;
}
void print_permutation() {
for (auto i = this->data.begin(); i != this->data.end(); ++i) {
for (auto j = i->begin(); j != i->end(); ++j) {
cout << *j << " ";
}
cout << '\n';
}
}
//计算余子式
Permutation cal_Cofactor(int row,int col) {
vector<int>row_data; vector<vector<int>>temp_data;
for (int i = 0; i < this->rank; ++i) {
if (i == row - 1)continue;
for (int j = 0; j < this->rank; ++j) {
if (j == col - 1)continue;
row_data.push_back(this->data.at(i).at(j));
}
temp_data.push_back(row_data);
row_data.clear();
}
return Permutation(this->rank - 1, temp_data);
}
//递归通过代数余子式计算
int calculate() {
int n = 0;
if (this->rank == 1)return this->data.at(0).at(0);
for (int i = 0; i < this->rank; ++i) {
n += this->data.at(0).at(i) * pow(-1, i + 2) * this->cal_Cofactor(1, i + 1).calculate();
}
return n;
}
};
然后继续递归得到结果
main.cpp
#include"permutation.h"
int main() {
cout<< Permutation(4,
{ 3, -1, 0, 7,
1, 0, 1, 5,
2, 3, -3, 1,
0, 0, 1, -2}).calculate()<<'\n';
cout << "~~~~~~~~~~~~~~~~~~~~~~" << '\n';
Permutation(1, { 1 }).print_permutation();
return 0;
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/126576.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...