Spfa模板
程序员文章站
2022-03-01 15:01:20
...
Spfa模板
#include<cstdio>
#include<queue>
#include<cstring>
#define maxm 10005
#define maxn 105
#define INF 0x3f3f3f3f
using namespace std;
struct Edge{
int to,cost,next;
}edge[maxm];
bool vis[maxn];
int dis[maxn],head[maxn],n,m,cnt;
void Init(){
memset(vis,false,sizeof(vis)); //个人觉得用一个for来初始化时间复杂度更小
memset(head,-1,sizeof(head)); //head初始化为-1,cnt为0
cnt = 0;
for(int i=1; i<=n; i++)
dis[i] = (i==1)? 0 : INF;
}
void add(int from,int to,int cost){
edge[cnt].to = to;
edge[cnt].cost = cost;
edge[cnt].next = head[from];
head[from] = cnt++;
}
void Spfa(int s){
int u;
queue<int> Q;
Q.push(s); //注意进队列
dis[s] = 0;
vis[s] = true;
while(!Q.empty()){
u = Q.front();
Q.pop(); //注意出队列
vis[u] = false;
for(int i=head[u]; i!=-1; i=edge[i].next){
int v = edge[i].to;
int w = edge[i].cost; //这两处的用i是指与U相连的边都进行松弛!
if(dis[v] > dis[u] + w){
dis[v] = dis[u] + w;
if(!vis[v]){
vis[v] = true;
Q.push(v); //注意进队列
}
}
}
}
}