Advertisement
Guest User

Untitled

a guest
Dec 14th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 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 _030_Backtracking
  8. {
  9. class Backtracking
  10. {
  11. protected int[] st; // stiva solutie
  12. protected int top; // varful stivei
  13. protected int dimmax; //dimensiunea maxima a stivei
  14. protected int vmin, vmax; //valoarea minima si maxima care se pot pune pe un nivel de stiva
  15. public Backtracking(int _top, int _dimmax, int _vmin, int _vmax)
  16. {
  17. top = _top;
  18. dimmax = _dimmax;
  19. vmin = _vmin;
  20. vmax = _vmax;
  21. }
  22. public virtual void Afisare()
  23. {
  24. int i;
  25. for (i = 1; i <= top; i++)
  26. Console.Write(st[i] + " ");
  27. Console.WriteLine();
  28. }
  29. public virtual bool Valid()
  30. {
  31. return true;
  32. }
  33. public void Back()
  34. {
  35. bool cand;
  36. while (top > 0)
  37. {
  38. cand = false;
  39. while(!cand && st[top] < vmax)
  40. {
  41. st[top]++;
  42. cand = Valid();
  43. }
  44. if(!cand) top--;
  45. else if(top == dimmax) Afisare();
  46. else
  47. st[++top] = vmin;
  48. }
  49. }
  50. }
  51. class Permutari : Backtracking
  52. {
  53. public Permutari(int _top, int _dimmax, int _vmin, int _vmax)
  54. : base(_top, _dimmax, _vmin, _vmax)
  55. {
  56. st = new int[dimmax + 1];
  57. }
  58. public override bool Valid()
  59. {
  60. int i;
  61. for(i = 1; i < top; i++)
  62. if(st[i] == st[top]) return false;
  63. return true;
  64. }
  65. }
  66. //Se dau S,n. Sa se scrie S ca suma de numere naturale
  67. //nenule distincte
  68. // S = 12, n = 3 : (1,2,9) (1,3,8) ... (3,4,5)
  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.  
  79. public override bool Valid()
  80. {
  81. int s = 0;
  82. if (st[top-1] >= st[top]) return false;
  83. for (int i = 0; i <= top; i++)
  84. s += st[i];
  85. if (s > S) return false;
  86. if (top == dimmax && s != S)
  87. return false;
  88. return true;
  89. }
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement