BZOJ 4152: [AMPPZ2014]The Captain Dijkstra+贪心
Code:
#include <queue> #include <cstdio> #include <cstring> #include <algorithm> #define N 400005 #define ll long long #define setIO(s) freopen(s".in","r",stdin) using namespace std; ll d[N]; int n,edges; int hd[N],to[N<<1],nex[N<<1],val[N<<1],done[N]; void addedge(int u,int v,int c) { nex[++edges]=hd[u],hd[u]=edges,to[edges]=v,val[edges]=c; swap(u,v); nex[++edges]=hd[u],hd[u]=edges,to[edges]=v,val[edges]=c; } struct Point { int x,y,id; }e[N]; bool cmpx(Point a,Point b) { return a.x<b.x; } bool cmpy(Point a,Point b) { return a.y<b.y; } struct Node { int u; ll dis; Node(int u=0,ll dis=0):u(u),dis(dis){} bool operator<(Node b) const { return b.dis<dis; } }; priority_queue<Node>q; void Dijkstra() { int s=1; memset(d,0x3f,sizeof(d)); for(d[s]=0,q.push(Node(s,0));!q.empty();) { Node e=q.top(); q.pop(); int u=e.u,i,v; if(done[u]) continue; done[u]=1; for(i=hd[u];i;i=nex[i]) { v=to[i]; if(d[v]>d[u]+val[i]) { d[v]=d[u]+val[i]; q.push(Node(v,d[v])); } } } } int main() { int i,j,k; // setIO("input"); scanf("%d",&n); for(i=1;i<=n;++i) { int x,y; scanf("%d%d",&e[i].x,&e[i].y), e[i].id=i; } sort(e+1,e+1+n,cmpx); for(i=2;i<=n;++i) addedge(e[i-1].id,e[i].id,e[i].x-e[i-1].x); sort(e+1,e+1+n,cmpy); for(i=2;i<=n;++i) { addedge(e[i-1].id,e[i].id,e[i].y-e[i-1].y); } Dijkstra(); printf("%lld\n",d[n]); return 0; }