邮递员的烦恼

邮递员的烦恼

原文链接

邮递员的烦恼 题解插图

#include<bits/stdc++.h>
#define ll int
#define fd(i, a, b) for (ll i = a; i >= b; i--)
#define r(i, a) for (ll i = fir[a]; i; i = e[i].nex)
#define file(a) freopen(#a ".in", "r", stdin);freopen(#a ".out", "w", stdout);
#define il inline
#define gc getchar()
#define f(i,a,b) for(ll i=a;i<=b;i++)
using namespace std;
const ll maxn=6e2+10,INF=1e16;
ll n,X[maxn],Y[maxn],nx,ny,Cnt,fir[maxn*maxn<<1];
ll cx,cy;
il ll number(ll x,ll y){return (x-1)*cy+y;}
il ll read(){
    ll x=0,f=1;char ch=gc;
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc;}
    while(ch>='0'&&ch<='9') x=(x*10)+(ch^48),ch=gc;
    return x*f;
}
struct node{ll x,y;}p[maxn];
struct edge{ll to,nex,w;}e[maxn*maxn<<1];
il void add(ll a,ll b,ll c){
	e[++Cnt].to=b,e[Cnt].nex=fir[a],e[Cnt].w=c;
	fir[a]=Cnt;
}
ll xa[5]={0,0,0,1,-1};
ll ya[5]={0,1,-1,0,0};
ll wx[maxn],wy[maxn];
ll yx[maxn],yy[maxn];
bool g[maxn*maxn];
il bool pd(ll x,ll y){return (x>0&&x<=cx&&y>0&&y<=cy);}
il ll far(ll x1,ll y1,ll x2,ll y2){return abs(wx[x1]-wx[x2])+abs(wy[y1]-wy[y2]);}
il void Add(ll x,ll y){
	ll num=number(x,y);
	f(i,1,4){
		ll vx=x+xa[i],vy=y+ya[i];
        if(!pd(vx,vy)) continue;
		ll c=far(x,y,vx,vy);
		ll k=number(vx,vy);
		add(num,k,c);add(k,num,c);
	}
}
priority_queue<pair<ll,ll> >q;
ll dis[maxn*maxn],inf;
il void dijkstra(ll x){
	memset(dis,0x7f,sizeof(dis));
	inf=dis[0];
	dis[x]=0;
	// cout<<x<<endl;
	q.push(make_pair(0,x));
	while(!q.empty()){
		ll u=q.top().second;
		// cout<<u<<endl;
		q.pop();
		// if(g[u]&&u!=x) continue;
		r(i,u){
			ll v=e[i].to;
			// cout<<v<<endl;
			if(dis[u]+e[i].w<dis[v]){
				dis[v]=dis[u]+e[i].w;
				if(!g[v])q.push(make_pair(-dis[v],v));
			}
		}
	}
}
ll xcnt,ycnt;
int main()
{
	file(delite);
	n=read();
	f(i,1,n){
		p[i].x=read(),p[i].y=read();
		X[++xcnt]=p[i].x,Y[++ycnt]=p[i].y;
		X[++xcnt]=p[i].x+1;
		X[++xcnt]=p[i].x-1;
		Y[++ycnt]=p[i].y+1;
		Y[++ycnt]=p[i].y-1;
	}
	sort(X+1,X+1+xcnt);
	sort(Y+1,Y+1+ycnt);
	nx=unique(X+1,X+1+xcnt)-X-1;
	ny=unique(Y+1,Y+1+ycnt)-Y-1;
	f(i,1,n){
		p[i].x=lower_bound(X+1,X+1+nx,p[i].x)-X;
		p[i].y=lower_bound(Y+1,Y+1+ny,p[i].y)-Y;
	}
	// f(i,1,n) cout<<p[i].x<<" "<<p[i].y<<endl;
	f(i,1,nx){
		wx[++cx]=X[i];
		yx[i]=cx;
	}
	f(i,1,ny){
		wy[++cy]=Y[i];
		yy[i]=cy;
	}
	f(i,1,n) g[number(yx[p[i].x],yy[p[i].y])]=1;
	// cout<<cx<<" "<<cy<<endl;
	f(i,1,cx) f(j,1,cy) Add(i,j);
	p[n+1]=p[1];
	ll ans=0;
	f(i,1,n){
		// cout<<i<<endl;
		ll x=yx[p[i].x];
		ll y=yy[p[i].y];
		// cout<<x<<" "<<y<<endl;
		ll x1=yx[p[i+1].x];
		ll y1=yy[p[i+1].y];
		// cout<<number(x,y)<<endl;
		dijkstra(number(x,y));
		// cout<<dis[number(x1,y1)]<<endl;
		ans+=dis[number(x1,y1)];
		// cout<<ans<<endl;
		if(dis[number(x1,y1)]==inf){
			cout<<-1;
			return 0;
		}
	}
	cout<<ans<<endl;
}
/*
4
2 2
2 4
2 1
1 3
*/
posted @ 2021-10-13 10:00  yf1987  阅读(58)  评论(0编辑  收藏  举报