Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <iostream>
- #include <iomanip>
- #include <cmath>
- #include <fstream>
- using namespace std;
- ifstream fin ("in.txt");
- ofstream fout ("out.txt");
- const double eps = 10e-9;
- void print(const vector<vector<double>> & v) {
- for (auto & row : v) {
- for (auto & it : row)
- fout << setw(12) << (fabs(it) > eps ? it : 0);
- fout << endl;
- }
- }
- vector<double> solve(vector<vector<double>> & D) {
- fout << "Input:" << endl;
- print(D);
- fout << endl;
- int m = D.size(), n = D.front().size(), now = 0;
- for (int j = 0, i; j < n-1; ++j) {
- int max = now;
- for (i = now+1; i < m; ++i)
- if (fabs(D[i][j]) > fabs(D[max][j]))
- max = i;
- if ( fabs(D[max][j]) < 10e-9 ) continue;
- swap(D[max], D[now]);
- for (i = now+1; i < m; ++i) {
- if ( !D[i][j] ) continue;
- double c = D[i][j] / D[now][j];
- for (int k = j; k < n; ++k)
- D[i][k] -= c * D[now][k];
- }
- ++now;
- }
- fout << "First:" << endl;
- print(D);
- fout << endl;
- now = m-1;
- for (int j = n-2; j >= 0; --j, --now) {
- if ( !D[now][j] ) continue;
- for (int i = now-1; i >= 0; --i) {
- if ( !D[i][j] ) continue;
- double c = D[i][j] / D[now][j];
- for (int k = n-1; k >= 0; --k)
- D[i][k] -= c * D[now][k];
- }
- }
- fout << "Second:" << endl;
- print(D);
- fout << endl;
- vector<double> answer(m, 0);
- for (int i = 0; i < m; ++i)
- if ( D[i][i] ) {
- D[i].back() /= D[i][i];
- D[i][i] = 1;
- answer[i] = D[i].back();
- }
- return answer;
- }
- int main() {
- int n;
- fin >> n;
- vector<vector<double>> s(n, vector<double>(n+1, 0));
- for (auto & row : s)
- for (auto & it : row)
- fin >> it;
- auto a = solve(s);
- fout << "Answer:" << endl;
- for (auto & it : a)
- fout << setw(12) << (fabs(it) > eps ? it : 0);
- fout << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement