大水一道,直接切爆。
我们需要记录每一行有哪些车站,每一列有哪些车站。
然后spfa。spfa队列头是起点,每次拓展的时候枚举哪些车站在当前行/列,每次去到一个点,就看一下是否可以更新答案。
#include<bits/stdc++.h>
#define N 100010
#define inf 2147483647
#define ll long long
#define point(a) multiset<a>::iterator
#define mod (ll)(500000)
#define mem(a,b) memset(a,b,sizeof (a))
#define open(x) freopen(x".in","r",stdin);freopen(x".out","w",stdout);
using namespace std;
struct st
{
ll x,y;
}home,school,s[N];
struct edge
{ll v,fr;}h[N],l[N];
ll n,m,i,j,k,ans,toth,totl;
ll tailh[N],taill[N],f[N],q[N*50];
void addh(ll u,ll v)
{
h[++toth].v=v;
h[toth].fr=tailh[u];
tailh[u]=toth;
}
void addl(ll u,ll v)
{
l[++totl].v=v;
l[totl].fr=taill[u];
taill[u]=totl;
}
void updata(st a,ll dis)
{
ll x=a.x,y=a.y;
if(x!= school.x && y!=school.y)return ;
if(x == school.x )
dis+= 2*abs(y - school.y); else dis+= 2*abs(x - school.x);
ans=(ans==-1) || (ans>dis) ? dis :ans;
}
void spfa()
{
mem(f,127);
ll i=0,j=1;
s[0]=home;
f[0]=0;
q[1]=0;
while(i++<j)
{
ll u=q[i%mod],x=s[u].x,y=s[u].y;
for(ll ph=tailh[x];ph;ph=h[ph].fr)
{
ll v=h[ph].v,dec=abs(y - s[v].y);
if(f[u] + 1 + 2*dec < f[v])
{
f[v]=f[u] + 1 +2*dec;
updata(s[v],f[v]);
if(!(s[v].x == school.x && s[v].y == school.y))q[(++j)%mod]=v;
}
}
for(ll pl=taill[y];pl;pl=l[pl].fr)
{
ll v=l[pl].v,dec=abs(x - s[v].x);
if(f[u] + 1 + 2*dec < f[v])
{
f[v]=f[u] + 1 +2*dec;
updata(s[v],f[v]);
if(!(s[v].x == school.x && s[v].y == school.y))q[(++j)%mod]=v;
}
}
}
return ;
}
int main()
{
open("station");
scanf("%lld%lld",&n,&m);
for(i=1;i<=m;i++)
{
scanf("%lld%lld",&s[i].x,&s[i].y);
addh(s[i].x,i); //第s[i].x行 - > 第i个车站
addl(s[i].y,i);
}
scanf("%lld%lld%lld%lld",&home.x,&home.y,&school.x,&school.y);
ans=-1;
spfa();
printf("%lld",ans);
return 0;
}