回家

大水一道,直接切爆。
我们需要记录每一行有哪些车站,每一列有哪些车站。
然后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;
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值