Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define MAX 107
- #define INF 1e18
- using namespace std;
- typedef long long ll;
- struct way{
- ll x, y;
- ll val, tmp;
- way(ll _x, ll _y,ll _val, ll _tmp): x(_x), y(_y), val(_val), tmp(_tmp) {}
- bool operator >(const way& other) const {
- return x > other.x;
- }
- };
- ll dist[MAX][MAX], grid[MAX][MAX];
- ll n, m,k;
- int _x[4] = {1, 0, -1, 0};
- int _y[4] = {0, 1, 0, -1};
- bool check(ll x, ll y){
- return x >= 0 && x < n && y >= 0 && y < m;
- }
- void dijkstra(ll l, ll c){
- priority_queue<way*,vector<way*> , greater<way*> > q;
- q.push(new way(l, c, 0LL, 0LL));
- dist[l][c] = 0LL;
- while(!q.empty()){
- way* actual = q.top();
- q.pop();
- ll xp = actual->x;
- ll yp = actual->y;
- ll peso = actual->val;
- if(peso > dist[xp][yp]) continue;
- for(int i = 0; i < 4; i++){
- ll x = xp + _x[i];
- ll y = yp + _y[i];
- if(check(x, y)){
- ll val = peso;
- if(grid[xp][yp] == -1 && grid[x][y] == -1) val++;
- else if(grid[xp][yp] == -1){
- if(actual->tmp >= grid[x][y]) val += (k-actual->tmp) + grid[x][y];
- else val += grid[x][y]-actual->tmp;
- }else if(grid[x][y] == -1) val++;
- else if(grid[x][y] == 0 && grid[xp][yp] == k-1) val++;
- else if(grid[x][y]-grid[xp][yp] != 1) continue;
- else val++;
- if(val < dist[x][y]){
- dist[x][y] = val;
- q.push(new way(x, y, val, val%k));
- }
- }
- }
- }
- }
- void enche(){
- for(int i = 0; i <= n; i++){
- for(int j = 0; j <= m; j++) dist[i][j] = INF;
- }
- }
- void print(){
- for(int i = 0; i < n; i++){
- for(int j = 0; j < m; j++) cout << dist[i][j] << " \n"[j == m-1];
- }
- }
- int main(){
- scanf("%lld %lld %lld", &n, &m, &k);
- for(int i = 0; i < n; i++){
- for(int j = 0; j < m; j++) scanf("%lld", &grid[i][j]);
- }
- enche();
- dijkstra(0,0);
- printf("%lld\n", (dist[n-1][m-1] == INF) ? -1LL: dist[n-1][m-1]);
- //print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement