spfa 40 哪里写的不对吗
查看原帖
spfa 40 哪里写的不对吗
874087
huihuihuihui楼主2023/4/22 09:25
#include<iostream>
#include<cmath>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;

const int N = 1e4 + 10;

bool st[N];
int n,m,k,e[N],h[N],ne[N],idx,dist[N],w[N];

void add(int a , int b , int c){
	e[idx] = b;
	w[idx] = c;
	ne[idx] = h[a];
	h[a] = idx++;
	
}

void spfa(){
	memset(dist,0x3f,sizeof dist);
	dist[k] = 0;
	queue<int> q;
	q.push(k);
	st[k] = true;
	while(q.size()){
		int t = q.front();
		q.pop();
		st[t] = false;
		for(int i = h[t] ; i != -1 ; i = ne[i]){
			int j = e[i];
			if(dist[j] > dist[t] + w[i]){
				dist[j] = dist[t] + w[i];
				if(!st[j]){
					st[j] = true;
					q.push(j);
				}
			}
		}
	}
	
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	memset(h,-1,sizeof h);
	cin >> n >> m >> k;
	for(int i = 0 ; i < m ; i ++){
		int a ,b ,c;
		cin >> a >> b >> c;
		add(a,b,c);
	}
	spfa();
	for(int i = 1 ; i <= n ; i ++){
		if(dist[i] == 0x3f3f3f3f)
			cout<< 2147483647 << " ";
		else cout << dist[i] << " ";
	}
	return 0;
}```
2023/4/22 09:25
加载中...