Advertisement
tomalikem

Untitled

May 24th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <cstdio>
  2. #include <queue>
  3.  
  4. using namespace std;
  5.  
  6. struct tile {
  7.     int i, j;
  8.     int d;
  9. };
  10.  
  11. struct TileComparator {
  12.     bool operator()(const tile* lhs, const tile* rhs) const {
  13.         return lhs->d < rhs->d;
  14.     }
  15. };
  16.  
  17. int find(int x, int* parent) {
  18.     while(parent[x] != x) {
  19.         parent[x] = parent[parent[x]];
  20.         x = parent[x];
  21.     }
  22.     return x;
  23. }
  24.  
  25. void unia(int x, int y, int* parent) {
  26.     int rootX = find(x, parent);
  27.     int rootY = find(y, parent);
  28.     parent[rootX] = rootY;
  29. }
  30.  
  31. const int DX[4]={1,0,-1,0};
  32. const int DY[4]={0,1,0,-1};
  33. int draught_calculator(tile*** map, priority_queue<tile*,  vector<tile*>, TileComparator> Q, int n, int k) {
  34.     //if(n==1) return map[0][0]->d; doesn't work either way
  35.     int* parent = new int[n*n];
  36.     for(int i=0;i<n*n;i++) {
  37.         parent[i] = i;
  38.     }
  39.  
  40.     while(!Q.empty() && find(0, parent) != find(n*n-1, parent)) {
  41.         tile* tmp = Q.top(); Q.pop();
  42.         if(tmp->d < k) {
  43.             k = tmp->d;
  44.         }
  45.  
  46.         for (int i=0;i<4;i++) {
  47.             int x = tmp->i + DX[i];
  48.             int y = tmp->j + DY[i];
  49.             if (x>=0 && x<n && y>=0 && y<n && map[x][y]->d >= tmp->d) {
  50.                 unia(n*tmp->i+tmp->j, n*x+y, parent);
  51.             }
  52.         }
  53.     }
  54.     return k;
  55. }
  56.  
  57. int main ()
  58. {
  59.     int Z;
  60.     scanf("%d", &Z);
  61.     while(Z--)
  62.     {
  63.         int n, k;
  64.         scanf ("%d %d", &n, &k);
  65.  
  66.         tile ***map = new tile**[n];
  67.         for (int i = 0; i < n; i++)
  68.             map[i] = new tile*[n];
  69.              
  70.         priority_queue<tile*, vector<tile*>, TileComparator> Q;
  71.         int depth;
  72.  
  73.         for (int i = 0; i < n; i++) {
  74.             for (int j = 0; j < n; j++) {
  75.                 tile *til = new tile;
  76.                 til->i = i;
  77.                 til->j = j;
  78.                 scanf("%d", &til->d);
  79.                 Q.push(til);
  80.                 map[i][j] = til;
  81.             }
  82.         }
  83.  
  84.         int result = draught_calculator(map, Q, n, k);
  85.         printf ("%d\n", k-result);
  86.         for (int i = 0; i < n; i++)
  87.             delete[] map[i];
  88.         delete[] map;
  89.     }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement