1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #define maxn 100010 #define Maxn 300010 #define cn const node #define cQ const Queue #define ll long long #define INF 1000000000000000000ll using namespace std;
int m, n;
int sx, sy, tx, ty;
struct node { int x, y;
node() {} node(int _x, int _y) { x = _x; y = _y; } } a[maxn];
int X[maxn], Y[maxn], cnt1, cnt2; void init_hash() { for (int i = 1; i <= n; ++i) X[i] = a[i].x, Y[i] = a[i].y; sort(X + 1, X + n + 1); cnt1 = unique(X + 1, X + n + 1) - X - 1; sort(Y + 1, Y + n + 1); cnt2 = unique(Y + 1, Y + n + 1) - Y - 1; for (int i = 1; i <= n; ++i) { a[i].x = lower_bound(X + 1, X + cnt1 + 1, a[i].x) - X; a[i].y = lower_bound(Y + 1, Y + cnt2 + 1, a[i].y) - Y; } }
struct Edge { int to, next, w; } e[8 * maxn]; int c1, head[Maxn]; inline void add_edge(int u, int v, int w) { e[c1].to = v; e[c1].w = w; e[c1].next = head[u]; head[u] = c1++; }
inline void Add_edge(int u, int v, int w) { add_edge(u, v, w); add_edge(v, u, w); }
struct Queue { int k; ll v;
Queue() {} Queue(int _k, ll _v) { k = _k; v = _v; }
friend bool operator < (cQ &u, cQ &v) { return u.v > v.v; } }; priority_queue<Queue> Q; bool vis[Maxn]; ll dis[Maxn]; int s, t; void dijkstra() { Q.push(Queue(s, 0)); for (int i = 1; i <= cnt1 + cnt2 + n; ++i) dis[i] = INF; dis[s] = 0; while (!Q.empty()) { int u = Q.top().k; Q.pop(); if (vis[u]) continue; vis[u] = 1; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, w = e[i].w; if (dis[v] > dis[u] + w) { dis[v] = dis[u] + w; Q.push(Queue(v, dis[v])); } } } } int main() { memset(head, -1, sizeof head); cin >> m >> n >> sx >> sy >> tx >> ty; for (int i = 1; i <= n; ++i) cin >> a[i].x >> a[i].y; a[++n] = node(sx, sy); init_hash(); s = cnt1 + cnt2 + n; for (int i = 1; i <= n; ++i) { int x = a[i].x, y = a[i].y, id = i + cnt1 + cnt2; Add_edge(id, x, 0); Add_edge(id, cnt1 + y, 0); } for (int i = 1; i < cnt1; ++i) Add_edge(i, i + 1, X[i + 1] - X[i]); for (int i = 1; i < cnt2; ++i) Add_edge(cnt1 + i, cnt1 + i + 1, Y[i + 1] - Y[i]); dijkstra(); ll ans = INF; for (int i = 1; i <= n; ++i) ans = min(ans, dis[i + cnt1 + cnt2] + abs(X[a[i].x] - tx) + abs(Y[a[i].y] - ty)); cout << ans << endl; return 0; }
|