edutedu

partitii backtracking

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