Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <math.h>
- using namespace std;
- template <typename T>
- vector<vector<T>> ExtractMinor(vector<vector<T>> a, int x, int y);
- template <typename T>
- T MinorDeterminant(vector<vector<T>> a) {
- if (a.size() != a[0].size()) {
- throw new exception("Матрица не квадратная.");
- }
- if (a.size() == 2) {
- return a[0][0] * a[1][1] - a[0][1] * a[1][0];
- }
- else {
- T result = 0;
- for (int i = 0; i < a.size(); i++) {
- result += pow(-1, i) * a[0][i] * MinorDeterminant(ExtractMinor<T>(a, i, 0));
- }
- return result;
- }
- }
- template <typename T>
- vector<vector<T>> ExtractMinor(vector<vector<T>> a, int x, int y) {
- int c = 0;
- vector<vector<T>> other;
- for (int i = 0; i < a.size(); i++) {
- if (i != y) {
- other.resize(other.size() + 1);
- for (int j = 0; j < a[0].size(); j++) {
- if (j != x) {
- other[c].push_back(a[i][j]);
- }
- }
- c++;
- }
- }
- return other;
- }
- template <typename T>
- vector<T> KramerMethod(vector<vector<T>> a, vector<T> b) {
- if (a.size() != a[0].size()) {
- throw new exception("Матрица не квадратная.");
- }
- if (a[0].size() != b.size()) {
- throw new exception("Длина b не равна размерности a");
- }
- vector<T> dets;
- T det = MinorDeterminant<T>(a);
- if (det == 0) {
- throw new exception("Нет решений");
- }
- for (int i = 0; i < a.size(); i++) {
- vector<vector<T>> other = a;
- for (int j = 0; j < a.size(); j++) {
- other[j][i] = b[j];
- }
- dets.push_back(MinorDeterminant<T>(other) / det);
- }
- return dets;
- }
- int main()
- {
- vector<vector<double>> a = { {2,3,-1},{1,-2,1},{1,0,2} };
- vector<double> b = { 9,3,2 };
- //Ответ: 4 0 -1
- vector<double> other = KramerMethod<double>(a, b);
- for (int i = 0; i < other.size(); i++) {
- cout << other[i] << " ";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement