Shortest circuit, Dijstra algorithm

Source: Internet
Author: User

#include <iostream>#include<stdio.h>#include<math.h>#include<vector>using namespacestd;structe{intnext,c;}; Vector<e> edge[101];BOOLmark[101];intdis[101];intMain () {intn,m;  while(Cin>>n>>m && n!=0&& m!=0){        intA,b,c;        e temp; //Initialize         for(intI=1; i<=n;i++) { edge[i].clear (); Dis[i]=-1; Mark[i]=false; } dis[1]=0; mark[1]=true;  while(m--) {cin>>a>>b>>C; TEMP.C=C; Temp.next=A;            Edge[b].push_back (temp); Temp.next=b;        Edge[a].push_back (temp); }                intnewp=1;  for(intI=1; i<n;i++){             for(intj=0; J<edge[newp].size (); j + +){                intnex=Edge[newp][j].next; intc =edge[newp][j].c; if(Mark[nex] = =true)                Continue; if(dis[nex]==-1|| DIS[NEX]&GT;DIS[NEWP]+C)//Floyd also have if not reach or smaller than, do not know why to have unreachable, first rememberDis[nex] = dis[newp]+C; }            intmin=100000000;  for(intj=1; j<=n;j++){                if(Mark[j] = =true)                Continue; if(Dis[j] = =-1)//because our infinity is not infinite, but-1, after the size of the impact                Continue;//so we need to add this condition .                if(dis[j]<min) {min=Dis[j]; NEWP=J; }} MARK[NEWP]=true; } cout<<dis[n]<<Endl; }    return 0;}

It feels much more troublesome to write code than Floyd. But Floyd is three times the complexity of N, the size of the solution graph cannot be greater than 200 nodes

Dijstra is the complexity of the square of N.

Adjacency linked list initialization of red I always forget

Core code Loop n-1 times, first update through the new node after the DIS, and then find the update after the recent become NEWP

Shortest circuit, Dijstra algorithm

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.