1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include <bits/stdc++.h>
const int kMaxT = 6e6 + 5, kMaxN = 3e3 + 5; const int kD4[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; const int kD8[][2] = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}, {0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int n, m, k; int sx, sy, tx, ty; std::vector<int> G[kMaxT]; std::string s[kMaxN];
void dijkstra() { std::vector<std::vector<std::pair<int, int>>> dis(n + 1, std::vector<std::pair<int, int>>(m + 1)); std::vector<std::vector<bool>> vis(n + 1, std::vector<bool>(m + 1)); std::priority_queue<std::tuple<int, int, int, int>> q; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) dis[i][j] = {1e9, 1e9}; dis[sx][sy] = {0, k - 1}; q.emplace(0, -(k - 1), sx, sy); for (; !q.empty();) { auto [d, w, x, y] = q.top(); q.pop(); if (vis[x][y]) continue; vis[x][y] = 1; for (auto [dx, dy] : kD4) { int tx = x + dx, ty = y + dy; if (tx < 1 || tx > n || ty < 1 || ty > m) continue; if (s[tx][ty] == '.') { std::pair<int, int> p = {dis[x][y].first, k - 1}; if (dis[tx][ty] > p) { dis[tx][ty] = p; q.emplace(-p.first, -p.second, tx, ty); } } std::pair<int, int> p = {dis[x][y].first + 1, 0}; if (dis[tx][ty] > p) { dis[tx][ty] = p; q.emplace(-p.first, -p.second, tx, ty); } } if (dis[x][y].second < k - 1) { for (auto [dx, dy] : kD8) { int tx = x + dx, ty = y + dy; if (tx < 1 || tx > n || ty < 1 || ty > m) continue; std::pair<int, int> p = {dis[x][y].first, dis[x][y].second + 1}; if (dis[tx][ty] > p) { dis[tx][ty] = p; q.emplace(-p.first, -p.second, tx, ty); } } } } std::cout << dis[tx][ty].first << '\n'; }
void dickdreamer() { std::cin >> n >> m >> k >> sx >> sy >> tx >> ty; for (int i = 1; i <= n; ++i) { std::cin >> s[i]; s[i] = " " + s[i]; } dijkstra(); }
int32_t main() { #ifdef ORZXKR freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif std::ios::sync_with_stdio(0), std::cin.tie(0), std::cout.tie(0); int T = 1; while (T--) dickdreamer(); return 0; }
|