Yibentong Part Three Data Structure Chapter Four Graph Theory Algorithm Section Two Shortest Path Algorithm 1382: Shortest Path (Spfa)

1382: Shortest path (Spfa)

Time limit: 1000 ms Memory limit: 65536 KB
Number of submissions: 2196 Number of passes: 592
[Title description]
Given MM edges, NN points weighted undirected graph. Find the shortest path from 11 to NN.

[Input] The
first line: N, M (N≤100000, M≤500000) N, M (N≤100000, M≤500000);

Next MM line 33 positive integers: ai, bi, ci indicate a path of length ci between ai and bi, ci≤1000ai, bi, ci indicate a path of length ci between ai, and bi, ci ≤1000.

[Output]
An integer, representing the shortest distance from 11 to NN.

[Input sample]
4 4
1 2 1
2 3 1
3 4 1
2 4 1
[Output sample]
2
[Prompt]
[Sample explanation]

Note that there may be heavy edges and self-loops in the figure, and the data ensures that there is a path connection between 11 and NN.

#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
const int NN=100001;
using namespace std;
struct node
{
    
    
	int from,go,money;
};
vector<int>g[NN];
vector<node>N;
bool inq[NN];
int d[NN];
queue<int>a;
int n,m;
void e(int from,int go,int money)
{
    
    
	N.push_back((node){
    
    from,go,money});
	g[from].push_back(N.size()-1);
}
int main()
{
    
    
	scanf("%d %d",&n,&m);
	fill_n(d,100002,999999);
	for(int i=1;i<=m;i++)
	{
    
    
		int x,y,z;
		scanf("%d %d %d",&x,&y,&z);
		e(x,y,z);
		e(y,x,z);
	}
	d[1]=0;
	a.push(1);
	inq[1]=true;
	while(!a.empty())
	{
    
    
		int u=a.front();
		a.pop();
		inq[u]=false;
		for(int i=0;i<g[u].size();i++)
		{
    
    
			node e=N[g[u][i]];
			if(e.money+d[u]<d[e.go])
			{
    
    
				d[e.go]=e.money+d[u];
				if(!inq[e.go])
				{
    
    
					a.push(e.go);
					inq[e.go]=true;
				}
			}
		}
	}
	printf("%d",d[n]);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44043668/article/details/86072465