Advertisement
mickypinata

GCJ2020-Q5: Indicium

Apr 4th, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. vector<vector<int>> board;
  6. int q, n;
  7. bool lock;
  8.  
  9. void PrintBoard(){
  10.     cout << "POSSIBLE\n";
  11.     for(int i = 0; i < n; ++i){
  12.         for(int j = 0; j < n; ++j){
  13.             cout << board[i][j] << " ";
  14.         }
  15.         cout << "\n";
  16.     }
  17.     return;
  18. }
  19.  
  20. bool Valid(int r, int c, int x){
  21.     for(int i = 0; i < n; ++i){
  22.         if(board[r][i] == x || board[i][c] == x){
  23.             return false;
  24.         }
  25.     }
  26.     return true;
  27. }
  28.  
  29. void Sudoku(int r, int c){
  30.     //cout << r << " " << c << "\n";
  31.     if(r == n && c == 0){
  32.         PrintBoard();
  33.         lock = true;
  34.         return;
  35.     } else if(board[r][c] != 0){
  36.         if(c == n - 1){
  37.             Sudoku(r + 1, 0);
  38.         } else {
  39.             Sudoku(r, c + 1);
  40.         }
  41.         return;
  42.     } else {
  43.         for(int j = 1; j <= n; ++j){
  44.             if(Valid(r, c, j) && !lock){
  45.                 board[r][c] = j;
  46.                 if(c == n - 1){
  47.                     Sudoku(r + 1, 0);
  48.                 } else {
  49.                     Sudoku(r, c + 1);
  50.                 }
  51.                 board[r][c] = 0;
  52.             }
  53.         }
  54.         return;
  55.     }
  56. }
  57.  
  58. void GenTrace(int i, int t){ /// i = 0 to n - 1
  59.     if(i == n){
  60.         if(t == 0 && !lock){
  61.             Sudoku(0, 0);
  62.         }
  63.     } else {
  64.         for(int j = 1; j <= n; ++j){
  65.             if(j <= t && !lock){
  66.                 board[i][i] = j;
  67.                 GenTrace(i + 1, t - j);
  68.                 board[i][i] = 0;
  69.             }
  70.         }
  71.     }
  72. }
  73.  
  74. int main(){
  75.  
  76.     int t;
  77.  
  78.     scanf("%d", &q);
  79.     for(int k = 1; k <= q; ++k){
  80.         scanf("%d %d", &n, &t);
  81.         board.assign(n, vector<int>(n, 0));
  82.         lock = false;
  83.         cout << "Case #" << k << ": ";
  84.         GenTrace(0, t);
  85.         if(!lock){
  86.             cout << "IMPOSSIBLE\n";
  87.         }
  88.     }
  89.  
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement