Algorithm Summary--dijkstra

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.