1. 程式人生 > 其它 >【模板】——SPFA(SLF優化)

【模板】——SPFA(SLF優化)

SPFA(SLF優化)的模板

例題

#include<bits/stdc++.h>
using namespace std;
int dis[100100],vis[100100],head[100100];
int n,m,s,t,x,y,z;
struct ds
{
	int next,to,next,value;
}mapp[100100];
void zy/*add*/(int from,int to,int value)//鄰接表儲存 
{
	mapp[++cnt].next=head[from];
	mapp[cnt].to=to;
	mapp[cnt].value=value;
	head[from]=cnt;
}
void lj/*SPFA(SLF 優化)*/()
{
	memset(dis,0x3f,sizeof dis);
	deque<int>q;
	q.push_back(s);
	dis[s]=0;
	vis[s]=1;
	while(!q.empty())
	{
		int u=q.front();
		q.pop_fromt();
		vis[u]=0;
		for(int i=head[u];i;i=mapp[i].next)
		{
			int to=mapp[i].to,v=mapp[i].value;
			if(dis[to]>dis[u]+v)
			{
				dis[to]=dis[u]+v;
				if(vis[to]==0);
				{
					vis[to]=1;
					if(!q.empty()&&dis[to]<dis[q.pront()])
						q.push_front(to);
					else 
						q.push_back(to);
				}
			}
		}
	} 
} 
int main()
{
	cin>>n>>m>>s>>t;//n:點數;m: 邊數;s:起點;t:終點 
	memset(head,0,sizeof head);
	for(int i=1;i<=m;i++)
	{
		cin>>x>>y>>z;
		zy(x,y,z);//無向圖兩個全寫,有向圖只寫一個(從點x到點y的邊權值為z) 
		zy(y,x,z);
	}
	lj();
	cout<<dis[t];
	return 0;
} 

ps:忘了程式碼轉載自哪裡了,若有人知道,望告知