Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include<iostream>
  2. #include <conio.h>
  3. using namespace std;
  4.  
  5. int n, k, s, x[101];
  6.  
  7. void initializare(int k)
  8. {
  9.     if(k == 1) x[k]=0;
  10.     else x[k] = x[k - 1] - 1;
  11. }
  12. int solutie()
  13. {
  14.     if(s == n) return 1;
  15.     return 0;
  16. }
  17. int valid(int k)
  18. {
  19.     if(s + x[k] <= n)
  20.     {
  21.         s = s + x[k];
  22.         return 1;
  23.     }
  24.     return 0;
  25. }
  26. void afisare(int k)
  27. {
  28.     for(int i = 1;i < k;i++)
  29.     cout << x[i] << " + ";
  30.     cout << x[k] << " = " << n;
  31.     cout << endl;
  32.     s = s - x[k];
  33. }
  34. void backTracking()
  35. {
  36.     k = 1;
  37.     initializare(k);
  38.     while(k > 0)
  39.     {
  40.         if(x[k] < n - s)
  41.         {
  42.             x[k]++;
  43.             if(valid(k))
  44.             if(solutie())
  45.             afisare(k);
  46.             else
  47.             {
  48.                 k++;
  49.                 initializare(k);
  50.             }
  51.         }
  52.         else
  53.         {
  54.             k--;
  55.             s = s - x[k];
  56.         }
  57.     }
  58. }
  59. int main()
  60. {
  61.     cout << "Dati un numar: ";
  62.     cin >> n;
  63.     cout << endl << "Numarul poate fi descompus ca urmatoarele sume de numere: " << endl;
  64.     backTracking();
  65.     return 0;
  66.     _getch();
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement