Several algorithms of graph theory shortest of

Several algorithms of graph theory shortest of

1.Floyd

Time complexity: O (v ^ 3) v : vertex ( vertex number (
Complexity Space: O (v ^ 2)

Thought: the DP
with G [i] [j] represents the minimum from vertex i to vertex j, and weight.
State transition equation: g [i] [j] = min (g [i] [j], g [i] [k] + g [k] [j])
straightforward means: vertex i to vertex j through vertices k and k takes a minimum value without vertices.
Initialization: INF distance between all points
see the following template code details:

for(int k=1;k<=n;k++)//k循环必须放在最外层,放在第二层或第三层都会WA 因为一个k相当一个中转站。应该先对一个中转站将所有点压缩距离,然后再进行下一个中转站。如果对一个点进行所有中转站的遍历则没有压缩距离的效果 
			for(int i=1;i<=n;i++)//总结就是状态的转移是通过不同的i j 而不是通过不同的k 所以k在最外层。
				    if(g[i][k]!=inf)//一个优化:如果i k 之间没有路径 直接进行下一个i. 
				for(int j=1;j<=n;j++)
					g[i][j]=min(g[i][j],g[i][k]+g[k][j]);//此处用if 比 min 快一点。

Floyd algorithm several places to note:
1. The time complexity greatly. It applies only to small-scale map.
2. triple loop in k must be explained in the outermost layer of the specific reason code.

Portal questions:
the Floyd bare title hdu2544
the Floyd transitive closure hdu1704

----------------------------------- be continued ------------ ------------------------

Published 18 original articles · won praise 14 · views 361

Guess you like

Origin blog.csdn.net/weixin_45750972/article/details/104483429