Advertisement
Guest User

Untitled

a guest
Dec 14th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace _026_Backtracking
  8. {
  9. class BackTracking
  10. {
  11. protected int[] st; // stiva solutiei
  12. protected int top; // varful stivei
  13. protected int dimmax; // dimensiunea maxima a stivei
  14. protected int vmin, vmax; // valorile minima si maxima care se pot
  15. // pune pe un inel de pe stiva
  16. public BackTracking(int _top, int _dimmax, int _vmin, int _vmax)
  17. {
  18. top = _top;
  19. dimmax = _dimmax;
  20. vmin = _vmin;
  21. vmax = _vmax;
  22. }
  23. public virtual void Afisare() // afisare solutie
  24. {
  25. int i;
  26. for (i = 1; i <= top; i++)
  27. Console.Write(st[i] + " ");
  28. Console.WriteLine();
  29. }
  30. public virtual bool Valid()
  31. {
  32. return true;
  33. }
  34. public void Back()
  35. {
  36. bool cand;
  37. while (top > 0)
  38. {
  39. cand = false;
  40. while (!cand && st[top] < vmax)
  41. {
  42. st[top]++;
  43. cand = Valid();
  44. }
  45. if (!cand) top--;
  46. else if (top == dimmax) Afisare();
  47. else st[++top] = vmin;
  48. }
  49. }
  50. }
  51.  
  52. class Permutari : BackTracking
  53. {
  54. public Permutari(int _top, int _dimmax, int _vmin, int _vmax)
  55. : base(_top, _dimmax, _vmin, _vmax)
  56. {
  57. st = new int[dimmax + 1];
  58. }
  59.  
  60. public override bool Valid()
  61. {
  62. int i;
  63. for (i = 1; i < top; i++)
  64. if (st[i] == st[top]) return false;
  65. return true;
  66. }
  67. }
  68.  
  69. class Sume : BackTracking
  70. {
  71. protected int S;
  72. public Sume(int _top, int _dimmax, int _vmin, int _vmax, int _S)
  73. : base(_top, _dimmax, _vmin, _vmax)
  74. {
  75. st = new int[dimmax + 1];
  76. S = _S;
  77. }
  78. public override bool Valid()
  79. {
  80. if (st[top - 1] >= st[top]) return false;
  81. int s = 0;
  82. for (int i = 1; i <= top; i++)
  83. s += st[i];
  84. if (s > S) return false;
  85. if (top == dimmax && s != S) return false;
  86. return true;
  87. }
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement