BZOJ4152:[AMPPZ2014]The Captain——题解
https://www.lydsy.com/JudgeOnline/problem.php?id=4152
给定平面上的n个点,定义(x1,y1)到(x2,y2)的费用为min(|x1-x2|,|y1-y2|),求从1号点走到n号点的最小费用。
先以纵坐标从下往上不考虑横坐标为例,发现我们付出代价一定是最近的两行之间的点的代价,于是对y排序,则相邻两个点连边即可。
横坐标同理。
#include<map> #include<cmath> #include<stack> #include<queue> #include<cstdio> #include<cctype> #include<vector> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define fi first #define se second; const int N=2e5+5; const int M=N*4; const int INF=2e9; inline int read(){ int X=0,w=0;char ch=0; while(!isdigit(ch)){w|=ch=='-';ch=getchar();} while(isdigit(ch))X=(X<<3)+(X<<1)+(ch^48),ch=getchar(); return w?-X:X; } struct node{ int x,y,id; }p[N]; struct edge{ int to,nxt,w; }e[M]; int n,cnt,head[N],dis[N]; priority_queue<pii,vector<pii>,greater<pii> >q; inline bool cmpx(node a,node b){ return a.x==b.x?a.y<b.y:a.x<b.x; } inline bool cmpy(node a,node b){ return a.y==b.y?a.x<b.x:a.y<b.y; } inline void add(int u,int v,int w){ e[++cnt].to=v;e[cnt].w=w;e[cnt].nxt=head[u];head[u]=cnt; } inline int len(node a,node b){ return min(abs(a.x-b.x),abs(a.y-b.y)); } void dij(int s){ for(int i=1;i<=n;i++)dis[i]=INF; dis[s]=0;q.push(pii(0,s)); while(!q.empty()){ int u=q.top().se;int f=q.top().fi;q.pop(); if(f!=dis[u])continue; for(int i=head[u];i;i=e[i].nxt){ int v=e[i].to,w=e[i].w; if(dis[v]>dis[u]+w){ dis[v]=dis[u]+w; q.push(pii(dis[v],v)); } } } } int main(){ n=read(); for(int i=1;i<=n;i++){ p[i].x=read(),p[i].y=read(); p[i].id=i; } sort(p+1,p+n+1,cmpx); for(int i=2;i<=n;i++){ int u=p[i-1].id,v=p[i].id,w=len(p[i-1],p[i]); add(u,v,w);add(v,u,w); } sort(p+1,p+n+1,cmpy); for(int i=2;i<=n;i++){ int u=p[i-1].id,v=p[i].id,w=len(p[i-1],p[i]); add(u,v,w);add(v,u,w); } dij(1); printf("%d\n",dis[n]); return 0; }
+++++++++++++++++++++++++++++++++++++++++++
+本文作者:luyouqi233。 +
+欢迎访问我的博客:http://www.cnblogs.com/luyouqi233/ +
+++++++++++++++++++++++++++++++++++++++++++