dzungchaos

CTDL&TT: Sắp xếp Hậu

May 31st, 2020
78
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. #include<math.h>
  3. using namespace std;
  4.  
  5. int a[20];
  6. int count;
  7.  
  8. bool Ok(int x2,int y2){
  9.     for(int i = 1; i < x2 ;i++)
  10.         if(a[i] == y2 || abs(i-x2) == abs(a[i] - y2) )
  11.             return false;
  12.     return true;
  13. }
  14.  
  15. void Xuat(int n){
  16.     cout << endl << ++count << ":  ";
  17.     for(int i = 1;i <= n;i++)
  18.         cout << a[i] << " ";        
  19.     cout << endl;
  20. }
  21.  
  22. void Try(int i,int n){
  23.     for(int j = 1;j <= n;j++){
  24.         if(Ok(i,j)){
  25.             a[i] = j;
  26.             if(i == n) Xuat(n);
  27.             Try(i+1,n);
  28.         }
  29.     }
  30. }
  31.  
  32. int main(){
  33.     cout << "Nhap n: ";
  34.     int n;
  35.     cin >> n;
  36.     cout << endl << "----- Cac cach sap xep: ----- " << endl;
  37.     Try(1,n);
  38.     if (count == 0) cout << "----- Khong co cach sap xep nao! -----" << endl;
  39.     cout << endl << "---- Co " << count << " cach sap xep cac con hau! ----" << endl;
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment