dude2099

Partitii Backtracking

Dec 4th, 2019
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int n, x[100],nrsol=0;
  6.  
  7. void init(int k)
  8. {
  9.     x[k]=0;
  10. }
  11.  
  12. int existaSuccesor(int k)
  13. {
  14.     return x[k]<n;
  15. }
  16.  
  17. int cont(int k)
  18. {
  19.     if(k>1 && x[k-1]>x[k])
  20.         return 0;
  21.     int s=0;
  22.     for(int i=1;i<=k;i++)
  23.         s+=x[i];
  24.     return s<=n;
  25. }
  26.  
  27. void tipar(int k)
  28. {
  29.     nrsol++;
  30.     for(int i=1;i<=k;i++)
  31.         cout<<x[i]<<" ";
  32.     cout<<endl;
  33. }
  34.  
  35. int solutie(int k)
  36. {
  37.     int s=0;
  38.     for(int i=1;i<=k;i++)
  39.         s+=x[i];
  40.     return n==s;
  41. }
  42.  
  43. void back(int k)
  44. {
  45.     init(k);
  46.     while(existaSuccesor(k))
  47.     {
  48.         x[k]++;
  49.         if(cont(k))
  50.         {
  51.             if(solutie(k))
  52.                 tipar(k);
  53.             else
  54.                 back(k+1);
  55.         }
  56.     }
  57. }
  58.  
  59. int main()
  60. {
  61.     cout<<"Care este numarul: "; cin>>n;
  62.     back(1);
  63.     cout<<"Solutii: "<<nrsol;
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment