Ultraviolet A 11573-ocean currents (BFS + priority queue)

Source: Internet
Author: User
Ultraviolet A 11573-ocean currents

Question Link

Given a sea surface, the number represents the current direction, and does not charge energy along the current. The reverse current consumes 1 point of energy. Each time you ask a start point, an endpoint is given, minimum energy consumption from the start point to the end point

Train of Thought: broad search, the queue uses a priority queue, each time the lowest energy point out for status transfer

Code:

#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;}


Ultraviolet A 11573-ocean currents (BFS + priority queue)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.