kburnik

C++ Memoizacija - uvod

Oct 19th, 2012
113
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. C++ radionica za napredne osnovce
  3.  
  4. TEMA : Memoizacija
  5.  
  6. Autor zadatka: Kristijan Burnik
  7.  
  8. Autor rjesenja: Kristijan Burnik
  9.  
  10. Datum rjesavanja: 19.10.2012.
  11.  
  12. */
  13. #include <iostream>
  14. #include <cstdlib>
  15. #include <vector>
  16.  
  17. using namespace std;
  18.  
  19. int calls = 0;
  20. int fib(int n) {
  21.     calls++;
  22.     return (n <= 2) ? 1 : (fib(n-2)+fib(n-1));
  23. }
  24.  
  25.  
  26. vector <long long> rj;
  27.  
  28. long long fib2(int n) {
  29.      calls ++ ;
  30.      if (rj.size() < (n+1))
  31.         rj.resize(n+1);
  32.        
  33.      if (rj[n] > 0) return rj[n];
  34.      
  35.      return rj[n] = (n <= 2) ? 1 : fib2(n - 2) + fib2(n - 1);
  36. }
  37.  
  38. int main() {
  39.  
  40.     int koji = 0;
  41.     cout << "Fib (rekurzivno) ili Fib2 (rekurzivno + memoizacija) ? " << endl << "Upisati 1 ili 2: ";
  42.     cin >> koji;
  43.    
  44.     cout << "N = ";
  45.  
  46.    
  47.     if (koji == 1) {
  48.        int n;
  49.        cin >> n;
  50.    
  51.         for (int i = 1; i <= n; i++) {
  52.            calls = 0 ;
  53.            cout << i << " " << fib(i) << " : " << calls << endl;
  54.         }
  55.              
  56.     } else {
  57.         int n;
  58.         cin >> n;
  59.    
  60.         for (int i = 1; i <= n; i++) {
  61.            rj.resize(0);
  62.            calls = 0 ;
  63.            cout << i << " " << fib2(i) << " : " << calls << endl;
  64.         }
  65.            
  66.     }
  67.  
  68.     system("pause");
  69.     return 0;
  70. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×