题意:一个(r*c<=5000)的迷宫,起点'Y‘,终点'C',陷阱‘#’,可行路‘*’(每走一个,*cost),传送门P,问Y到C的最短路
分析:一道最短路问题,加了传送门的功能,那么第一次走到P时是最短的路径,之后再到P都不会比第一次短,所以将所有P看成一个点,走过就vis掉,剩下就是简单的BFS了
收获:1、复习BFS求最短路 2. memset不能乱用,尤其是数组很大时,容易爆内存
代码:
/************************************************ * Author :Running_Time * Created Time :2015-8-22 11:56:55 * File Name :I.cpp ************************************************/ #include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 typedef long long ll; typedef pair<int, int> P; const int N = 5e3 + 10; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; int dx[4] = {-1, 1, 0, 0}; int dy[4] = {0, 0, -1, 1}; struct Node { int x, y, step; }; Node t[N/10]; char maze[N][N]; bool vis[N][N]; int n, m, cost, tot; int sx, sy, ex, ey; bool judge(int x, int y) { if (x < 1 || x > n || y < 1 || y > m || vis[x][y] || maze[x][y] == '#') return false; return true; } int BFS(void) { // memset (vis, false, sizeof (vis)); // memset (d, INF, sizeof (d)); for (int i=1; i<=n; ++i) { for (int j=1; j<=m; ++j) vis[i][j] = false; } vis[sx][sy] = true; queue<Node> Q; Q.push (Node {sx, sy, 0}); while (!Q.empty ()) { Node u = Q.front (); Q.pop (); for (int i=0; i<4; ++i) { int tx = u.x + dx[i], ty = u.y + dy[i]; if (!judge (tx, ty)) continue; vis[tx][ty] = true; if (maze[tx][ty] == 'C') { return u.step; } if (maze[tx][ty] == 'P') { for (int i=1; i<=tot; ++i) { t[i].step = u.step; Q.push (t[i]); vis[t[i].x][t[i].y] = true; } } else { Q.push (Node {tx, ty, u.step + 1}); } } } return -1; } int main(void) { while (scanf ("%d%d%d", &n, &m, &cost) == 3) { sx = sy = 0; ex = ey = 0; tot = 0; for (int i=1; i<=n; ++i) { scanf ("%s", maze[i] + 1); for (int j=1; j<=m; ++j) { if (maze[i][j] == 'Y') { sx = i, sy = j; } else if (maze[i][j] == 'C') { ex = i, ey = j; } else if (maze[i][j] == 'P') { t[++tot].x = i; t[tot].y = j; } } } int res = BFS (); if (res != -1) { printf ("%d ", res * cost); } else puts ("Damn teoy!"); } return 0; }