SPFA双端队列优化。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<deque> #define maxv 100050 #define maxe 400050 #define inf 0x7f7f7f7f using namespace std; struct edge { int v,w,nxt; }e[maxe]; int n,m,s,t1,t2,nume=0,g[maxv],dis[maxv],a,b,c,ans=inf; bool vis[maxv]; deque <int> q; void addedge(int u,int v,int w) { e[++nume].v=v; e[nume].w=w; e[nume].nxt=g[u]; g[u]=nume; } void spfa(int x) { while (!q.empty()) q.pop_front(); memset(vis,false,sizeof(vis)); fill(dis+1,dis+n+1,inf); q.push_front(x);vis[x]=true;dis[x]=0; while (!q.empty()) { int head=q.front();q.pop_front();vis[head]=false; for (int i=g[head];i;i=e[i].nxt) { int v=e[i].v; if (dis[v]>dis[head]+e[i].w) { dis[v]=dis[head]+e[i].w; if (!vis[v]) { if (q.empty()) q.push_front(v); else if (dis[v]<dis[q.front()]) q.push_front(v); else q.push_back(v); } } } } } int main() { scanf("%d%d%d%d%d",&m,&n,&s,&t1,&t2); for (int i=1;i<=m;i++) { scanf("%d%d%d",&a,&b,&c); addedge(a,b,c); addedge(b,a,c); } spfa(t1); ans=dis[s]+dis[t2]; spfa(t2); ans=min(ans,dis[s]+dis[t1]); printf("%d\n",ans); return 0; }