[Template] Dijkstra

Dijkstra

给定一个n个点m条边的有向图,图中可能存在重边和自环,所有边权均为正值。

请你求出1号点到n号点的最短距离,如果无法从1号点走到n号点,则输出-1

输入格式
第一行包含整数n和m。

接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。

输出格式
输出一个整数,表示1号点到n号点的最短距离。

如果路径不存在,则输出-1

数据范围
1≤n≤500,
1≤m≤105,
图中涉及边长均不超过10000

输入样例:
3 3
1 2 2
2 3 1
1 3 4
输出样例:
3
Dijkstra is a single-source shortest path problem:

Time complexity: O (n ^ 2)
Space complexity: n ^ 2
Condition: there is no negative side right

DijkstraOrder algorithm:
1. Initialization
2. cycle
3. minimum not found in S dist, and then it was added S
4. t is updated by other points dist

The main code (do not know if see Note)

const int N=510;
int dist[N];//用于储存1~i的最短距离
bool st[N];//标记是否已是最短距离
int g[N][N],n;//g数字用来储存邻接矩阵,n为点个数
int dijkstra()
{
	memset(dist,0x3f,sizeof(dist));//赋值为大数
	dist[1]=0;//赋值....
	for(int i=0;i<n-1;i++)//搜索n-1遍
	{
		int t=-1;//赋值为很小的数
		for(int j=1;j<=n;j++)//挨个搜索
			if(!st[j] and (t==-1 or dist[t]>dist[j]))//没搜过/更优解
				t=j;//更新t的值
		for(int j=1;j<=n;j++)
			dist[j]=min(dist[j],dist[t]+g[t][j]); //用t来更新其他值
		st[t]=true;//已搜过t
	}
	if(dist[n]==0x3f3f3f3f) return -1;//无解
	return dist[n];//有解
}

Well, the last question include this ACcode!
C ++ Code:

#include<iostream>
#include<cstring>//memset的头文件
using namespace std;
const int N=510;
int dist[N];
bool st[N];
int g[N][N],n,m;
int dijkstra()//迪杰斯特拉算法,具体描述见上↑
{
	memset(dist,0x3f,sizeof(dist));
	dist[1]=0;
	for(int i=0;i<n-1;i++)
	{
		int t=-1;
		for(int j=1;j<=n;j++)
			if(!st[j] and (t==-1 or dist[t]>dist[j]))
				t=j;
		for(int j=1;j<=n;j++)
			dist[j]=min(dist[j],dist[t]+g[t][j]); 
		st[t]=true;
	}
	if(dist[n]==0x3f3f3f3f) return -1;
	return dist[n];
}
int main()
{
	ios::sync_with_stdio(false);//输入优化,使cin与scanf相差无几
	cin>>n>>m;
	memset(g,0x3f,sizeof(g));//赋值为大数
	for(int i=1;i<=m;i++)//邻接矩阵的输入&存储
	{
		int x,y,z;
		cin>>x>>y>>z;
		g[x][y]=min(g[x][y],z);//更新
	}
	int t=dijkstra();
	cout<<t;//输出
	return 0;
}

Solution to a problem is not easy to write, save one point chanting ~

Published 35 original articles · won praise 30 · views 5281

Guess you like

Origin blog.csdn.net/user_qym/article/details/104086809