SPFA 代码+注释

SPFA 代码+注释

*本人傻逼所以一下全部为英语就是因为看着更简单易懂

#include "bits/stdc++.h"


//what SPFA is trying to do is it will find the first dot and go looking for it's neibores which means dots that have an connection with it
//then it will add pop it's self and add all the neiboring dots to the queue
//next if the new dots can do some help see line 48 then add it to the queue
//and you always have an bool saving what is inside the queue and what is not
//somedot can be inside the queue more the a time but there can't be two of the same dot inside the queue at one time
//if there are a time which one dot is in the queue more than once it's likly that there is a loop or a negtive loop see line 53
//SPFA IS O(E*2)//E MEANS EDGE


using namespace std;
const int maxN=400040 ;
struct Edge {
    
    
	int to , next , w ;

} e[ maxN ];

int n,m,cnt,p[ maxN ],Dis[ maxN ];
int In[maxN ];
bool visited[ maxN ];

void Add_Edge ( const int x , const int y , const int z ) {
    
    
	e[++cnt].to=y ;
	e[cnt].next=p[x];
	e[cnt].w=z;
	p[ x ]=cnt;
	return ;
}

bool Spfa(const int S) {
    
    
	int i,t,temp;
	queue<int> Q;
	memset ( visited , 0 , sizeof ( visited ) ) ;
	memset ( Dis , 0x3f , sizeof ( Dis ) ) ;
	memset ( In , 0 , sizeof ( In ) ) ;

	Q.push ( S ) ;
	visited [ S ] = true ;
	Dis [ S ] = 0 ;
	while( !Q.empty()){
    
    
		t = Q.front();
		Q.pop();
		visited[t]=false;
		for( i=p[t];i;i=e[i].next){
    
    
			temp=e[i].to ;
			if(Dis[temp]>Dis[t]+e[i].w){
    
    
				Dis[temp]=Dis[t]+e[i].w ;
				if( !visited[ temp ] ) {
    
    
					Q.push(temp);
					visited[temp]=true;
					if(++In[temp]>n)return false;
				}
			}
		}
	}
	return true;
}
int main ( ) {
    
    
	int S,T;
	scanf ( "%d%d%d%d" , &n , &m , &S , &T ) ;
	for(int i=1; i<=m ; ++i ) {
    
    
		int x,y,_;
		scanf("%d%d%d",&x,&y,&_ );
		Add_Edge(x,y,_) ;
	}
	if ( !Spfa ( S ) ) printf ( "FAIL!\n" ) ;
	else printf ( "%d\n" , Dis[ T ] 	) ;
	return 0;
}

//SPFA 万岁!! 

求点赞关注
有问题问我
CSP-J-S 2021 rp++!!

Guess you like

Origin blog.csdn.net/weixin_45446715/article/details/120638950