UVA 11573,uva11573

來源:互聯網
上載者:User

UVA 11573,uva11573
UVA 11573 - Ocean Currents

題目連結

題意:給定一個海面,數字分別代表海流方向,順著海流不用費能量,逆海流要費1點能量,每次詢問給一個起點一個終點,問起點到終點耗費的最小能量

思路:廣搜,隊列用優先隊列,每次取能量最低的點出來進行狀態的轉移

代碼:

#include <cstdio>#include <cstring>#include <queue>using namespace std;const int d[8][2] = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}};const int N = 1005;int n, m, vis[N][N];char g[N][N];struct Node {int x, y, val;Node() {}Node(int x, int y, int val) {this->x = x;this->y = y;this->val = val;}bool operator < (const Node& c) const {return val > c.val;}void read() {scanf("%d%d", &x, &y);}}s, e;int bfs() {priority_queue<Node> Q;s.val = 0;Q.push(s);memset(vis, -1, sizeof(vis));vis[s.x][s.y] = 0;while (!Q.empty()) {Node u = Q.top();if (u.x == e.x && u.y == e.y) return u.val;Q.pop();for (int i = 0; i < 8; i++) {int xx = u.x + d[i][0];int yy = u.y + d[i][1];int val = u.val;if (xx < 1 || xx > n || yy < 1 || yy > m) continue;if (i != g[u.x][u.y] - '0')val++;if (vis[xx][yy] == -1 || val < vis[xx][yy]) {vis[xx][yy] = val;Q.push(Node(xx, yy, val));}}}}int main() {while (~scanf("%d%d", &n, &m)) {for (int i = 1; i <= n; i++)scanf("%s", g[i] + 1);int q;scanf("%d", &q);while (q--) {s.read();e.read();printf("%d\n", bfs());}}return 0;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.