SPFA求次短路


#include <bits/stdc++.h>
#include <queue>
using namespace std;
int n,m,vis[5010],dis[5010][2],head[5010],nxt[200010],to[200010],tot,eg[200010];

int read() {
    
    
	int sum=0,fg=1;
	char c=getchar();
	while(c<'0'||c>'9') {
    
    
		if(c=='-')fg=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9') {
    
    
		sum=sum*10+c-'0';
		c=getchar();
	}
	return sum*fg;
}

void add(int x,int y,int c){
    
    
	tot++;
	nxt[tot]=head[x];
	to[tot]=y;
	eg[tot]=c;
	head[x]=tot;
}

void spfa(int s) {
    
    
	memset(dis,0x3f3f3f,sizeof(dis));
	dis[s][0]=0;
	//dis[i][0] means getting to point i the fastest way
	//dis[i][1] means getting to point i the second fastest way
	vis[s]=0;
	queue<int>q;
	q.push(s);
	while(!q.empty()) {
    
    
		int now=q.front();
		q.pop();
		vis[now]=0;
		for(int i=head[now]; i; i=nxt[i]) {
    
    
			int v=to[i];
			if(dis[v][0]>dis[now][0]+eg[i]) {
    
    
				//only the fastest way can make another fastest way
				//the second fastest way can not do so
				//if there is a way faster than the fastest way than the fastest way will change to be the now fastest
				//and the second fastest way will become the old fastest way
				dis[v][1]=dis[v][0];
				dis[v][0]=dis[now][0]+eg[i];
				if(!vis[v]) {
    
    
					q.push(v);
					vis[v]=1;
				}

			}
			if(dis[v][1]>dis[now][0]+eg[i]&&dis[v][0]<dis[now][0]+eg[i]) {
    
    
				//if there exists a way faster than the second fastest way but slower than the fastest way
				//then change second fastest way
				
				//if there is a way that the fastest way can remake the second fastest way but can not remake the fastest way
				//then only change the second fastest way
				dis[v][1]=dis[now][0]+eg[i];
				if(!vis[v]) {
    
    
					q.push(v);
					vis[v]=1;
				}
			}
			if(dis[v][1]>dis[now][1]+eg[i]) {
    
    
				
				//anyway the second fasteset way can't anyhow become the fastest way so if there is 
				//a way that the new second fastest way can be faster than the now second fastest way then replace
				
				//this is only possible to make the second fastest way
				dis[v][1]=dis[now][1]+eg[i];
				if(!vis[v]) {
    
    
					q.push(v);
					vis[v]=1;
				}
			}
		}
	}
}

int main() {
    
    
	n=read();
	m=read();
	for(int i=1; i<=m; i++) {
    
    
		int a,b,c;
		a=read();
		b=read();
		c=read();
		add(a,b,c);
		add(b,a,c);
	}
	spfa(1);
	cout<<dis[n][1];

	return 0;
}

Guess you like

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