#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]>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