Advertisement
Alx09

Ex4- B - Backtraking

Jun 1st, 2020
990
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define natural unsigned short
  5. #define maxN 10000
  6. unsigned v[maxN], n;
  7. static char st[] = { 0, 'a', 'a', 'a','b','b','b','b', 'c', 'c', 'c' };
  8. natural m, p, q;
  9. void Init(natural k) {
  10.     v[k] = 0;
  11. }
  12. natural Succesor(natural k) {
  13.     if (v[k] < n) {
  14.         v[k]++;
  15.         return 1;
  16.     }
  17.     return 0;
  18. }
  19.  
  20. natural Valid(natural k) {
  21.     natural i;
  22.     for (i = 1; i < k; i++)
  23.         if (v[i] == v[k])
  24.             return 0;
  25.     return 1;
  26. }
  27.  
  28. natural Solution(natural k) {
  29.     return (k == n);
  30. }
  31.  
  32. void Print() {
  33.     natural i;
  34.  
  35.     for (i = 1; i <= n; i++)
  36.         printf("%c", st[v[i]]);
  37.  
  38.     printf("\n");
  39. }
  40.  
  41. void Back() {
  42.     natural k = 1, isS, isV;
  43.     Init(k);
  44.     while (k > 0) {
  45.         isS = 0; isV = 0;
  46.         if (k <= n)
  47.             do {
  48.                 isS = Succesor(k);
  49.                 if (isS) isV = Valid(k);
  50.             } while (isS && !isV);
  51.             if (isS)
  52.                 if (Solution(k))
  53.                     Print();
  54.                 else {
  55.                     k++;
  56.                     Init(k);
  57.                 }
  58.             else
  59.                 k--;
  60.     }
  61. }
  62.  
  63. int main() {
  64.     n = 10;
  65.     Back();
  66.     system("pause");
  67.     return 0;
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement