1. 程式人生 > >BZOJ 4152 【AMPPZ2014】船長【建圖優化跑最短路】

BZOJ 4152 【AMPPZ2014】船長【建圖優化跑最短路】

兩個排序進行建圖優化:

#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#define db double
#define sg string
#define ll long long 
#define rel(i,x,y) for(ll i=(x);i<(y);i++)
#define rep(i,x,y) for(ll i=(x);i<=(y);i++)
#define red(i,x,y) for(ll i=(x);i>=(y);i--)
#define res(i,x) for(ll i=head[x];i;i=nxt[i])
using namespace std;

const ll N=2e5+5;
const ll Inf=1e18;
ll n,m,dis[N],vis[N];
ll cnt,to[N<<2],edge[N<<2],nxt[N<<2],head[N<<1];

#define _abs(x) ((x)>0?(x):(-(x)))

struct node {
	ll id,x,y;
}g[N];

struct nnode {
	ll num,dis;
	bool operator < (const nnode &a) const {
		return a.dis<dis;
	}
};

inline ll read() {
	ll x=0;char ch=getchar();bool f=0;
	while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return f?-x:x;
}

void ins(ll x,ll y,ll z) {
	to[++cnt]=y;edge[cnt]=z;nxt[cnt]=head[x];head[x]=cnt;
}

bool cmp1(node x,node y) {
	return x.x<y.x;
}

bool cmp2(node x,node y) {
	return x.y<y.y;
}

void dij(ll s) {
	priority_queue<nnode>pq;
	rep(i,1,n) dis[i]=Inf;dis[s]=0;
	nnode tmp;tmp.num=s;pq.push(tmp);
	
	while(pq.size()) {
		ll x=pq.top().num;pq.pop();
		
		if(!vis[x]) {
			vis[x]=1;
			res(i,x) {
				ll y=to[i],z=edge[i];
				
				if(!vis[y]&&dis[y]>dis[x]+z) {
					dis[y]=dis[x]+z;
					tmp.num=y;tmp.dis=dis[y];pq.push(tmp);
				}
			}
		}
	}
}

void File() {
	freopen("best.in","r",stdin);
	freopen("best.out","w",stdout);
}

int main() {
//	File();
	
	n=read();
	
	rep(i,1,n) g[i].x=read(),g[i].y=read(),g[i].id=i;
	
	sort(g+1,g+1+n,cmp1);
	
	rel(i,1,n) {
		ins(g[i].id,g[i+1].id,min(_abs(g[i].x-g[i+1].x),_abs(g[i].y-g[i+1].y)));
		ins(g[i+1].id,g[i].id,min(_abs(g[i].x-g[i+1].x),_abs(g[i].y-g[i+1].y)));
	}
	
	sort(g+1,g+1+n,cmp2);
	
	rel(i,1,n) {
		ins(g[i].id,g[i+1].id,min(_abs(g[i].x-g[i+1].x),_abs(g[i].y-g[i+1].y)));
		ins(g[i+1].id,g[i].id,min(_abs(g[i].x-g[i+1].x),_abs(g[i].y-g[i+1].y)));
	}

	dij(1);
	
	printf("%lld\n",dis[n]);
	
	return 0;
}