Dijkstra algorithm (find the shortest distance to any point)

Source: Internet
Author: User

Idea: First find the shortest point, that is, starting point, starting from the beginning, to find the shortest side, at the same time mark the starting point is true (Representative has been visited), access to the point will not have to visit, go down, to ensure that each found edge is the shortest side

To the end no side can be updated on behalf of

Look at the code

#include <iostream>#include<cstdio>#include<cstring>#include<stdio.h>#include<string.h>#include<cmath>#include<math.h>#include<algorithm>#include<Set>#include<queue>#include<map>typedefLong Longll;using namespacestd;Constll mod=1e9+7;Const intmaxn=1e3+Ten;Const intmaxk= -+Ten;Const intmaxx=1e4+Ten;Constll maxe= ++Ten;#defineINF 0x3f3f3f3f3f3fintV,e;ll COST[MAXN][MAXN];//Cost[u][v] Represents the weight of the Edge (U,V)ll D[MAXN];//The minimum distance from the starting point to the pointBOOLVIS[MAXN];voidSolveints) {     for(intI=0; i<v;i++) {D[i]=INF; } memset (Vis,false,sizeof(VIS)); D[s]=0;  while(true)    {        intflag=-1;  for(intI=0; i<v;i++)        {            //find points in all points for which the minimum distance has not been used            if(!vis[i]&& (flag==-1|| d[i]<D[flag])) Flag=i; }        if(flag==-1)             Break; Vis[flag]=true;  for(intI=0; i<v;i++) {D[i]=min (d[i],d[flag]+Cost[flag][i]); }    }     for(intI=0; i<v;i++) cout<<d[i]<<" "; cout<<Endl;}intMain () {Ios::sync_with_stdio (false); CIN>>v>>e;  for(intI=0; i<v;i++)    {         for(intj=0; j<v;j++) Cost[i][j]=INF; }    intA,b,va;  for(intI=0; i<e;i++) {cin>>a>>b>>va; COST[A][B]=va; } Solve (0); return 0;}

Dijkstra algorithm (find the shortest distance to any point)

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.