【题目链接】
【算法】
按x轴排序,将相邻点连边
按y轴排序,将相邻点连边
然后对这个图跑最短路就可以了,笔者用的是dijkstra算法
【代码】
#include<bits/stdc++.h>
using namespace std;
#define MAXN 200000
struct info {
int id,x,y;
} a[MAXN+10];
int N,i;
int dist[MAXN+10];
vector< pair<int,int> > E[MAXN+10];
template <typename T> inline void read(T &x) {
int f = 1; x = 0;
char c = getchar();
for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
x *= f;
}
template <typename T> inline void write(T x) {
if (x < 0) { putchar('-'); x = -x; }
if (x > 9) write(x/10);
putchar(x%10+'0');
}
template <typename T> inline void writeln(T x) {
write(x);
puts("");
}
inline bool cmp1(info a,info b) { return a.x < b.x; }
inline bool cmp2(info a,info b) { return a.y < b.y; }
inline void add_edge(int x,int y,int d) {
E[x].push_back(make_pair(y,d));
E[y].push_back(make_pair(x,d));
}
inline void dijkstra() {
int i,x,to,cost;
static int vis[MAXN+10];
priority_queue< pair<int,int> > q;
for (i = 2; i <= N; i++) dist[i] = INT_MAX;
q.push(make_pair(0,1));
while (!q.empty()) {
x = q.top().second; q.pop();
if (vis[x]) continue;
for (i = 0; i < E[x].size(); i++) {
to = E[x][i].first;
cost = E[x][i].second;
if (dist[x] + cost < dist[to]) {
dist[to] = dist[x] + cost;
q.push(make_pair(-dist[to],to));
}
}
}
}
int main() {
read(N);
for (i = 1; i <= N; i++) {
read(a[i].x); read(a[i].y);
a[i].id = i;
}
sort(a+1,a+N+1,cmp1);
for (i = 2; i <= N; i++) add_edge(a[i-1].id,a[i].id,a[i].x-a[i-1].x);
sort(a+1,a+N+1,cmp2);
for (i = 2; i <= N; i++) add_edge(a[i-1].id,a[i].id,a[i].y-a[i-1].y);
dijkstra();
writeln(dist[N]);
return 0;
}