Dijkstra Shortest Path Algorithm Template (Dual Source)

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int vis[1005], dis[1005], cost[1005][1005];//vis is the marking springboard point, dis is the distance between each point and the starting point, cost is the weight of the record point and the point,
long long n,m,k;
long long t1,t2;//Define the start and end points as global variables.
void dij (int s, int e)
{
	for(int i=1;i<=n;i++)
	{
		cost[i][i]=0;
		dis[i]=cost[s][i];//t1 represents the starting point, t2 represents the end point,
	}
	memset(vis,0,sizeof(vis));//Initialize each point to 0, and assign it to 1 if it acts as a springboard
	vis[s]=1;//Mark the point that has acted as a springboard. At the beginning, the first starting point is the springboard point
	for(int i=1;i<n;i++)
	{
		int k=1e9-1;//Set k to a very large number
		for(int j=1;j<=n;j++)
		{
			if(!vis[j] && dis[j]<k)//Find the closest point to the springboard and this point does not act as a springboard
			{
				k=dis[j]; //Update the value of k to find the closest point to the current springboard
				s=j;//Record the current springboard
			}
		}
		vis[s]=1;//Mark the current springboard, in the next search process, this springboard will not be used
		for(int i=1;i<=n;i++ )
		{
			if(cost[s][i]<0x3f3f3f3f)
			dis[i]=min(dis[i],dis[s]+cost[s][i]);//The current springboard is point s, and it is judged that the distance between each point and the starting point is the closest,
			                                     //Or the distance between the starting point and each point through the springboard is closer, this process is called relaxation
		}
		if(s==e) return ;
	}
}
intmain()
{
	cin>>m>>n;
	int a,b,c,k,t,sum=0.0;
	memset(cost,0x3f,sizeof(cost));
	for(int i=1;i<=m;i++)
	{
		cin>>a>>b>>c;
		cost[a][b]=min(cost[a][b],c);//Without a square graph, the distance from point a to point b is c;
		cost[b][a]=min(cost[b][a],c);//Without a square graph, the distance from point b to point a is c;
	}
	cin>>a>>b;
	if(a>b) swap(a,b);//The starting point is a, the end point is b, the weights of a to b and b to a are the same!
	said(a,b);
	cout<<dis[b]<<endl;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325935528&siteId=291194637