Tranvick

Z-2

Sep 22nd, 2013
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. #include <queue>
  5.  
  6. using namespace std;
  7.  
  8. const int N = 1111;
  9. const int INF = 1e9;
  10. const int dx[] = {-1, -2, -2, -1, 1, 2, 2, 1}, dy[] = {-2, -1, 1, 2, 2, 1, -1, -2};
  11. int a[N][N], n, m, d[N][N], cur, xs, ys, xf, yf;
  12. queue<int> qx[3], qy[3];
  13.  
  14. void bfs() {
  15.     qx[cur].push(xs);
  16.     qy[cur].push(ys);
  17.     d[xs][ys] = 0;
  18.     while (!qx[0].empty() || !qx[1].empty() || !qx[2].empty()) {
  19.         int x = qx[cur].front(), y = qy[cur].front();
  20.         qx[cur].pop(); qy[cur].pop();
  21.         for (int t = 0; t < 8; ++t) {
  22.             int tx = x + dx[t], ty = y + dy[t];
  23.             if (tx < 1 || tx > n || ty < 1 || ty > m || a[tx][ty] == -1) continue;
  24.             int w = 1 + a[tx][ty];
  25.             if (d[tx][ty] > d[x][y] + w) {
  26.                 d[tx][ty] = d[x][y] + w;
  27.                 qx[(cur + w) % 3].push(tx);
  28.                 qy[(cur + w) % 3].push(ty);
  29.             }
  30.         }
  31.         if (qx[cur].empty()) cur = (cur + 1) % 3;
  32.         if (qx[cur].empty()) cur = (cur + 1) % 3;
  33.     }
  34. }
  35.  
  36. int main(){            
  37.     ifstream fin("in.txt");
  38.     ofstream fout("out.txt");
  39.     fin >> n >> m;
  40.     for (int i = 1; i <= n; ++i)
  41.         for (int j = 1; j <= m; ++j) {
  42.             fin >> a[i][j];
  43.             d[i][j] = INF;
  44.         }
  45.     fin >> xs >> ys >> xf >> yf;
  46.     bfs();
  47.     if (d[n][m] < INF) fout << d[xf][yf];
  48.     else fout << "No";
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment