题目: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
*/