SPFA模板求助
  • 板块学术版
  • 楼主Siegerkranz_2735
  • 当前回复4
  • 已保存回复4
  • 发布时间2022/10/29 13:15
  • 上次更新2023/10/27 05:12:12
查看原帖
SPFA模板求助
580202
Siegerkranz_2735楼主2022/10/29 13:15
#include <bits/stdc++.h>
using namespace std;
struct Edge{
	int next,to,w;
}edge[1000005];
int cnt,n,m,sta,end,head[1000005];
int is_q[1000005],dist[1000005];
inline void addedge(int u,int v,int w){
	edge[cnt].to=v;
	edge[cnt].w=w;
	edge[cnt].next=head[u];
	head[u]=cnt++;
}
void spfa(int start){
	queue<int> q;
	memset(is_q,0,sizeof(is_q));
	memset(dist,0x3f,sizeof(dist));
	q.push(start);
	is_q[start]=1;
	dist[start]=0;
	while(q.size()){
		int now=q.front();
		q.pop(),is_q[now]=0;
		for(int i=head[now];~i;i=edge[i].next){
			int j=edge[i].next;
			if(dist[now]+edge[i].w<dist[j]){
				dist[j]=dist[now]+edge[i].w;
				if(!is_q[j])is_q[j]=1,q.push(j);
			}
		}
	}
}
int main(){
	cin>>n>>m>>sta>>end;
	for(int a,b,c;m--;)cin>>a>>b>>c,addedge(a,b,c),addedge(b,a,c);
	spfa(sta);
	cout<<dist[end];
    return 0;
}/*
input
7 12
1 7
1 7 10
1 2 1
1 3 2
2 7 8
2 3 1
2 4 4
2 5 1
2 6 10
3 4 3
5 6 1
5 4 7
6 7 1

output
4
*/
2022/10/29 13:15
加载中...