神奇的spfa
#include <queue> #include <cstdio> #include <cstring> #include <iostream> #define N 1010 #define max(x, y) ((x) > (y) ? (x) : (y)) int n, mx, my; int dis[N][N]; bool map[N][N], vis[N][N]; int dx[4] = {0, -1, 0, 1}, dy[4] = {1, 0, -1, 0}; struct node { int x, y; node(int x = 0, int y = 0) : x(x), y(y) {} }; std::queue <node> q; inline int read() { int x = 0, f = 1; char ch = getchar(); for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1; for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0'; return x * f; } int main() { node u, v; int i, x, y; n = read(); x = read(); y = read(); memset(dis, 127, sizeof(dis)); dis[x][y] = 0; q.push(node(x, y)); for(i = 1; i <= n; i++) { x = read(); y = read(); map[x][y] = 1; mx = max(mx, x); my = max(my, y); } while(!q.empty()) { u = q.front(); q.pop(); vis[u.x][u.y] = 0; for(i = 0; i < 4; i++) { x = u.x + dx[i]; y = u.y + dy[i]; if(x >= 0 && x <= mx + 1 && y >= 0 && y <= my + 1 && dis[x][y] > dis[u.x][u.y] + map[x][y]) { dis[x][y] = dis[u.x][u.y] + map[x][y]; if(!vis[x][y]) { vis[x][y] = 1; q.push(node(x, y)); } } } } printf("%d ", dis[1][1]); return 0; }