[dij] Codeforces Round #675 (Div. 2) D. Returning Home
注意搜到终点就不要搜了,不然会TLE
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,a,b) for(ll i=a;i<=b;i++) #define per(i,a,b) for(ll i=a;i>=b;i--) #define go(i,a) for(ll i=head[a];i;i=e[i].to) #define endl '\n' #define mem(x) memset(x,0,sizeof(x)) const ll amn=1e6+5,inf=1e18; char a[amn]; ll n,m,k; ll head[amn],etot=0; struct eg{ ll to,u,v,w; eg(){} eg(ll to,ll u,ll v,ll w):to(to),u(u),v(v),w(w){} }e[amn<<1]; void add(ll u,ll v,ll w){ e[++etot]=eg(head[u],u,v,w); head[u]=etot; e[++etot]=eg(head[v],v,u,w); head[v]=etot; } struct nd{ ll x,y,i; nd(){} nd(ll x,ll y,ll i):x(x),y(y),i(i){} }np[amn]; bool cmp1(nd a,nd b){return a.x<b.x;} bool cmp2(nd a,nd b){return a.y<b.y;} ll gd(ll a,ll b){return abs(a-b);} ll ans=0; struct node{ ll i,d; node(){} node(ll i,ll d):i(i),d(d){} friend bool operator < (node a,node b){ return a.d>b.d; } }; ll vis[amn]; ll dis[amn]; void dij(ll st){ rep(i,0,m+1){ vis[i]=0; dis[i]=inf; } dis[st]=0; priority_queue<node> q; while(q.size())q.pop(); q.push(node(st,0)); while(q.size()){ node x=q.top();q.pop(); ll u=x.i,d=x.d; if(vis[u])continue; if(u==m+1)break; ///因为是优先队列,所以搜到终点就不用搜了,如果继续搜就会在TEST4那TLE vis[u]=1; go(i,u){ ll v=e[i].v,w=e[i].w; if(!vis[v]&&d+w<dis[v]){ dis[v]=d+w; q.push(node(v,dis[v])); } } } } int main(){ // ios::sync_with_stdio(0); ll T=1; // cin>>T; while(T--){ scanf("%lld%lld",&n,&m); ll sx,sy,fx,fy; scanf("%lld%lld%lld%lld",&sx,&sy,&fx,&fy); rep(i,1,m){ scanf("%lld%lld",&np[i].x,&np[i].y); np[i].i=i; } add(0,m+1,gd(sx,fx)+gd(sy,fy)); rep(i,1,m){ add(0,i,min(gd(sx,np[i].x),gd(sy,np[i].y))); add(i,m+1,gd(fx,np[i].x)+gd(fy,np[i].y)); } sort(np+1,np+1+m,cmp1); rep(i,2,m){ add(np[i-1].i,np[i].i,gd(np[i-1].x,np[i].x)); } sort(np+1,np+1+m,cmp2); rep(i,2,m){ add(np[i-1].i,np[i].i,gd(np[i-1].y,np[i].y)); } // rep(i,1,etot){ // cout<<e[i].to<<' '<<e[i].u<<' '<<e[i].v<<' '<<e[i].w<<endl; // } ans=1e18; dij(0); // rep(i,0,m+1)cout<<i<<' '<<dis[i]<<endl; printf("%lld\n",dis[m+1]); } }