Advertisement
Manioc

relogios

Aug 21st, 2018
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.21 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MAX 107
  3. #define INF 1e18
  4.  
  5. using namespace std;
  6. typedef long long ll;
  7.  
  8. struct way{
  9.     ll x, y;
  10.     ll val, tmp;
  11.  
  12.     way(ll _x, ll _y,ll _val, ll _tmp): x(_x), y(_y), val(_val), tmp(_tmp) {}
  13.     bool operator >(const way& other) const {
  14.         return x > other.x;
  15.     }
  16. };
  17. ll dist[MAX][MAX], grid[MAX][MAX];
  18. ll n, m,k;
  19.  
  20. int _x[4] = {1, 0, -1, 0};
  21. int _y[4] = {0, 1, 0, -1};
  22.  
  23. bool check(ll x, ll y){
  24.     return x >= 0 && x < n && y >= 0 && y < m;
  25. }
  26. void dijkstra(ll l, ll c){
  27.     priority_queue<way*,vector<way*> , greater<way*> > q;
  28.  
  29.     q.push(new way(l, c, 0LL, 0LL));
  30.     dist[l][c] = 0LL;
  31.     while(!q.empty()){
  32.         way* actual = q.top();
  33.         q.pop();
  34.         ll xp = actual->x;
  35.         ll yp = actual->y;
  36.         ll peso = actual->val;
  37.  
  38.         if(peso > dist[xp][yp]) continue;
  39.         for(int i = 0; i < 4; i++){
  40.             ll x = xp + _x[i];
  41.             ll y = yp + _y[i];
  42.             if(check(x, y)){
  43.                 ll val = peso;
  44.                
  45.                 if(grid[xp][yp] == -1 && grid[x][y] == -1) val++;
  46.                 else if(grid[xp][yp] == -1){
  47.                     if(actual->tmp >= grid[x][y]) val += (k-actual->tmp) + grid[x][y];
  48.                     else val += grid[x][y]-actual->tmp;
  49.                 }else if(grid[x][y] == -1) val++;
  50.                 else if(grid[x][y] == 0 && grid[xp][yp] == k-1) val++;
  51.                 else if(grid[x][y]-grid[xp][yp] != 1) continue;
  52.                 else val++;
  53.  
  54.                 if(val < dist[x][y]){
  55.                     dist[x][y] = val;
  56.                     q.push(new way(x, y, val, val%k));
  57.                 }
  58.             }
  59.         }
  60.     }
  61. }
  62.  
  63. void enche(){
  64.     for(int i = 0; i <= n; i++){
  65.         for(int j = 0; j <= m; j++) dist[i][j] = INF;
  66.     }
  67. }
  68.  
  69. void print(){
  70.     for(int i = 0; i < n; i++){
  71.         for(int j = 0; j < m; j++) cout << dist[i][j] << " \n"[j == m-1];
  72.     }
  73. }
  74. int main(){
  75.     scanf("%lld %lld %lld", &n, &m, &k);
  76.     for(int i = 0; i < n; i++){
  77.         for(int j = 0; j < m; j++) scanf("%lld", &grid[i][j]);
  78.     }
  79.     enche();
  80.     dijkstra(0,0);
  81.     printf("%lld\n", (dist[n-1][m-1] == INF) ? -1LL: dist[n-1][m-1]);
  82.     //print();
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement