ural 1325 Dirt(bfs最短路+优先队列)

题目:http://acm.timus.ru/problem.aspx?space=1&num=1325

题意:

给定N×M的矩阵,给定起点和终点。其中矩阵中,0表示墙,1表示可以走的点,2表示脏的点。每次从1走到2或者从2走到1都需要换一次鞋。每次走为八方向。求从起点到终点的换鞋次数最少的最短路是多少。输出最少换鞋次数和最短路。

思路:

bfs最短路,每次记录到点(x,y)的路径和换鞋次数。由于比较级为2个,所以采取优先队列,以换鞋次数为第一比较级,路径长度为第二比较级。

代码:

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>

using namespace std;
typedef long long ll;
typedef pair<int, int>pii;
const double PI = acos (-1.0);
const int INF = 0x3f3f3f3f;
const int N = 500 + 9;

struct point {
    int x, y, step, num;
    point() {}
    point (int x, int y, int step, int num) : x (x), y (y), step (step), num (num) {}
    bool operator < (const point& rhs) const {
        if (num == rhs.num) return step > rhs.step;
        return num > rhs.num;
    }
};
int n, m, sx, sy, ex, ey;
char s[N][N];
bool vis[N][N]; //注意vis数组不能用,因为这里有两个比较的变量step和num,自己在这里错了几次QAQ
int dir[][2] = {{ -1, 0}, { -1, 1}, { -1, -1}, {0, 1}, {0, -1}, {1, 0}, {1, -1}, {1, 1}};
point d[N][N];
bool bfs () {
    priority_queue<point>q;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) d[i][j] = point (i, j, INF, INF);
    d[sx][sy] = point (sx, sy, 0, 0);
    q.push (d[sx][sy] );
    while (!q.empty() ) {
        point t = q.top();
        q.pop();
        if (t.x == ex && t.y == ey) {
            d[ex][ey] = t;
            return 1;
        }
        for (int i = 0; i < 8; i++) {
            int num = t.num, step = t.step + 1;
            int x = t.x + dir[i][0], y = t.y + dir[i][1];

            if (x < 0 || y < 0 || x == n || y == m) continue;
            if (s[x][y] == '0') continue;
            //vis[x][y] = 1;
            if (s[t.x][t.y] != s[x][y]) num++;
            if (d[x][y].num > num || (d[x][y].num == num && d[x][y].step > step) ) {
                d[x][y] = point (x, y, step, num);
                q.push (d[x][y]);
            }
        }
    }
    return 0;
}

int main() {
    //freopen ("f.txt", "r", stdin);
    scanf ("%d%d%d%d%d%d", &n, &m, &sx, &sy, &ex, &ey);
    sx--, sy--, ex--, ey--;
    for (int i = 0; i < n; i++) scanf ("%s", s[i]);

    if (!bfs() ) puts ("0 0");
    else printf ("%d %d\n", d[ex][ey].step + 1, d[ex][ey].num);

    return 0;
}
/*
4 4
2 1
1 3
0220
1001
1001
0110
输出:
3 1

*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值