传送门
Solution
比较妙,考虑按照给出的式子,只有(x)相邻或者(y)相邻的才会走,不然一定会走到相邻的再走(x)或(y),所以直接排序两边然后最短路即可。
Code
/*
mail: mleautomaton@foxmail.com
author: MLEAutoMaton
This Code is made by MLEAutoMaton
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define ll long long
#define REP(a,b,c) for(int a=b;a<=c;a++)
#define re register
#define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
inline int gi(){
int f=1,sum=0;char ch=getchar();
while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
return f*sum;
}
const int N=400010;
struct point{
int x,y,id;
}p[N];
int n,front[N],cnt;
struct node{
int to,nxt,w;
}e[N<<1];
void Add(int u,int v,int w){e[++cnt]=(node){v,front[u],w};front[u]=cnt;}
bool cmpx(point a,point b){return a.x<b.x;}
bool cmpy(point a,point b){return a.y<b.y;}
typedef pair<int,int> pii;
#define mp make_pair
priority_queue<pii,vector<pii>,greater<pii> >q;
int dis[N],vis[N];
void dijkstra(){
memset(dis,63,sizeof(dis));dis[1]=0;q.push({0,1});
while(!q.empty()){
int u=q.top().second;q.pop();
if(vis[u])continue;vis[u]=1;
for(int i=front[u];i;i=e[i].nxt){
int v=e[i].to;
if(dis[v]>dis[u]+e[i].w){
dis[v]=dis[u]+e[i].w;q.push({dis[v],v});
}
}
}
}
int main(){
n=gi();
for(int i=1;i<=n;i++)p[i].x=gi(),p[i].y=gi(),p[i].id=i;
sort(p+1,p+n+1,cmpx);
for(int i=2;i<=n;i++){
Add(p[i].id,p[i-1].id,abs(p[i].x-p[i-1].x));
Add(p[i-1].id,p[i].id,abs(p[i].x-p[i-1].x));
}
sort(p+1,p+n+1,cmpy);
for(int i=2;i<=n;i++){
Add(p[i].id,p[i-1].id,abs(p[i].y-p[i-1].y));
Add(p[i-1].id,p[i].id,abs(p[i].y-p[i-1].y));
}
dijkstra();printf("%d
",dis[n]);
return 0;
}