Advertisement
dmkozyrev

tridiag.cpp

Feb 14th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <vector>
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <cmath>
  5. #include <fstream>
  6.  
  7. using namespace std;
  8.  
  9. ifstream fin ("in.txt");
  10. ofstream fout ("out_tridiag.txt");
  11.  
  12. const double eps = 10e-9;
  13.  
  14. void print(const vector<vector<double>> & v) {
  15.     for (auto & row : v) {
  16.         for (auto & it : row)
  17.             fout << setw(12) << (fabs(it) > eps ? it : 0);
  18.         fout << endl;
  19.     }
  20. }
  21.  
  22. vector<double> solve(vector<vector<double>> & D) {
  23.     int m = D.size(), n = D.front().size();
  24.    
  25.     vector<double> P(n, 0), Q(n, 0), x(n, 0);
  26.    
  27.     int cmul = 0, cdel = 2;
  28.     P.front() = -D[0][1]/D[0].front();
  29.     Q.front() = D[0].back()/D[0].front();
  30.    
  31.     for (int i = 1; i < m; ++i) {
  32.         double r = (D[i][i]+D[i][i-1]*P[i-1]);
  33.         ++cmul;
  34.         if (i != m-1) {
  35.             P[i] = -D[i][i+1]/r;
  36.             ++cdel;
  37.         }
  38.         Q[i] = (D[i].back()-D[i][i-1]*Q[i-1])/r;
  39.         ++cmul; ++cdel;
  40.     }
  41.    
  42.     x.back() = Q.back();
  43.     for (int i = n - 2; i >= 0; --i) {
  44.         x[i] = P[i]*x[i+1]+Q[i];
  45.         ++cmul;
  46.     }
  47.    
  48.     fout << "cmul = " << cmul << "\tcdel = " << cdel << "\tsum = " << cmul+cdel << endl;
  49.    
  50.     x.pop_back();
  51.     return x;
  52. }
  53.  
  54. int main() {
  55.     int n;
  56.     fin >> n;
  57.     vector<vector<double>> s(n, vector<double>(n+1, 0));
  58.    
  59.     for (auto & row : s)
  60.         for (auto & it : row)
  61.             fin >> it;
  62.    
  63.    
  64.     auto a = solve(s);
  65.    
  66.     fout << "Answer:" << endl;  
  67.     for (auto & it : a)
  68.         fout << setw(12) << (fabs(it) > eps ? it : 0);
  69.     fout << endl;
  70.    
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement