题目大意:给定平面上的 n 个点,定义 (x1,y1) 到 (x2,y2) 的费用为 min(∣x1−x2∣,∣y1−y2∣),求从 1 号点走到 n 号点的最小费用。2≤n≤2×105。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 2e5 + 10;
const int MAXM = 4e5 + 10;
struct edge {
ll v, w, nxt;
} e[MAXM << 2];
int head[MAXN], tot;
inline
void add(int u, int v, ll w) {
e[++tot] = { v, w, head[u] }, head[u] = tot;
}
struct node {
ll u, dis;
bool operator < (const node &rhs) const { return dis > rhs.dis; }
};
priority_queue<node> q;
bool vis[MAXN];
ll dis[MAXN];
inline
ll dijkstra(int s, int t) {
memset(dis, 0x3f, sizeof dis);
q.push({ s, 0 }), dis[s] = 0, vis[s] = 1;
while (!q.empty()) {
int u = q.top().u; q.pop();
for (int i = head[u], v; i; i = e[i].nxt) {
v = e[i].v;
if (!vis[v] && dis[v] > dis[u] + e[i].w) {
dis[v] = dis[u] + e[i].w, q.push({ v, dis[v] });
}
}
}
return dis[t];
}
struct pos {
int id, x, y;
} a[MAXN];
bool cmpx(pos p, pos q) {
return p.x == q.x ? p.y < q.y : p.x < q.x;
}
bool cmpy(pos p, pos q) {
return p.y == q.y ? p.x < q.x : p.y < q.y;
}
int n;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d%d", &a[i].x, &a[i].y), a[i].id = i;
sort(a + 1, a + n + 1, cmpx);
for (int i = 1, w; i < n; i++) {
w = min(abs(a[i].x - a[i + 1].x), abs(a[i].y - a[i + 1].y));
add(a[i].id, a[i + 1].id, w);
}
sort(a + 1, a + n + 1, cmpy);
for (int i = 1, w; i < n; i++) {
w = min(abs(a[i].x - a[i + 1].x), abs(a[i].y - a[i + 1].y));
add(a[i].id, a[i + 1].id, w);
}
printf("%lld", dijkstra(1, n));
}
样例都没过……
输入样例:
5
2 2
1 1
4 5
7 1
6 7
输出样例:
2