Advertisement
mateuspl

URI: 1033 - Quantas Chamadas Recursivas?

Jan 26th, 2016
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. typedef unsigned long long ull;
  6.  
  7. int countCalls(ull, int);
  8. int** matrixProduct(int**, int**, int);
  9. int callsFor(int**, int);
  10.  
  11. int MATRIX[3][3] = { { 1, 1, 1 }, { 1, 0, 0 }, { 0, 0, 1 } };
  12.  
  13. int main()
  14. {
  15.     int tc = 0;
  16.  
  17.     while (++tc)
  18.     {
  19.         ull num;
  20.         int base;
  21.         cin >> num >> base;
  22.  
  23.         if (num == 0 && base == 0)
  24.             break;
  25.  
  26.         ull calls = countCalls(num, base);
  27.  
  28.         cout << "Case " << tc << ": " << num << " " << base << " " << calls << endl;
  29.     }
  30.  
  31.     return 0;
  32. }
  33.  
  34. int countCalls(ull number, int base)
  35. {
  36.     if (number == 0ull || number == 1ull)
  37.         return 1;
  38.  
  39.     int** cache[64] = {NULL};
  40.     int calculated = 0;
  41.  
  42.     cache[0] = new int*[3];
  43.     cache[0][0] = MATRIX[0];
  44.     cache[0][1] = MATRIX[1];
  45.     cache[0][2] = MATRIX[2];
  46.  
  47.     number--;
  48.  
  49.     int bit = 63;
  50.  
  51.     while (number >> bit == 0x0) bit--;
  52.  
  53.     if (bit > calculated)
  54.     {
  55.         int b = calculated + 1;
  56.  
  57.         for (; b <= bit; b++)
  58.             cache[b] = matrixProduct(cache[b - 1], cache[b - 1], base);
  59.  
  60.         calculated = b - 1;
  61.     }
  62.  
  63.     int** result = cache[bit];
  64.  
  65.     while (--bit >= 0)
  66.         if (number & (0x1 << bit))
  67.             result = matrixProduct(result, cache[bit], base);
  68.  
  69.     return callsFor(result, base);
  70. }
  71.  
  72. int** matrixProduct(int** a, int** b, int base)
  73. {
  74.     int** result = new int*[3];
  75.  
  76.     for (int l = 0; l < 3; l++)
  77.     {
  78.         result[l] = new int[3];
  79.  
  80.         for (int c = 0; c < 3; c++)
  81.         {
  82.             result[l][c] = (
  83.                 a[l][0] * b[0][c] +
  84.                 a[l][1] * b[1][c] +
  85.                 a[l][2] * b[2][c]
  86.             ) % base;
  87.         }
  88.     }
  89.  
  90.     return result;
  91. }
  92.  
  93. int callsFor(int** matrix, int base)
  94. {
  95.     int result[3] = {0};
  96.  
  97.     for (int l = 0; l < 3; l++)
  98.         for (int c = 0; c < 3; c++)
  99.             result[l] += matrix[l][c];
  100.    
  101.     return result[0] % base;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement