Dijkstra:
Complexity: O (n^2)
Use: To find the shortest path from the beginning to the end, do not need to go to each point
Applicable conditions:
Principle: Using the adjacency matrix, the D array is used to record the minimum value, and p is used to mark whether this set of data is used.
Step: A large for, two small for, the first small for the minimum value in the current D, in order to get subscript, the second small for to update the map minimum, the results, loop the entire map n times
Template:
#include <cstdio>#include<cstring>using namespacestd;Const intINF =0x3f3f3f3f, MAX = -;intmin1,x,y,z,k,n,m;intMap[max][max],p[max],d[max];voidDijkstraintMap[][max],intN) { for(inti =1; I <= N; i++) D[i]=inf; d[1] =0; for(inti =1; I <= N; i++) {min1=inf; for(intj =1; J <= N; J + +){ if(!p[j] && D[j] <min1) {Min1=D[j]; K=J; }} P[k]=1; for(intj =1; J <= N; J + +){ if(!p[j] && d[j] > D[k] +Map[k][j]) d[j]= D[k] +Map[k][j]; }} printf ("%d", D[n]);}intMain () {memset (P,0,sizeof(p)); scanf ("%d%d",&n,&m); for(inti =1; I <= N; i++) for(intj =1; J <= N; J + +) Map[i][j]=inf; for(inti =1; I <= m; i++) {scanf ("%d%d%d",&x,&y,&z); Map[x][y]=Z; } Dijkstra (Map,n); return 0;}
Algorithm Summary--dijkstra