Single source Shortest path, the first thought is Dijkstra. The idea of Dijkstra algorithm is not verbose, summed up is to keep the current node to the target node of the shortest distance.
The main idea (not to interpret the translation, the drawing is expressed): There are n vertices and T-edge of the graph, the number of vertices from 1th to the number of vertices of the shortest distance is how much.
Sample Input: ( first t after n!) First T after n! First T after n! )
5 5
1 2 20//Two vertices v1, v2, and weights between them
2 3 30
3 4 20
4 5 20
1 5 100
Sample Output:
90
Because it is relatively simple, it does not require too much comment.
1#include <iostream>2#include <cstdio>3#include <cstring>4 #defineSize 10015 #defineINF 0x3f3f3f3f6 using namespacestd;7 intn,t,a,b,c,i,j,k;8 intLand[size][size],dis[size],flag[size];9 Ten intMinintAintb//Tree Maintenance There can be a judgment statement, or you can use this to select the smaller one . One { A return((a) < (b))?(a):(B); - } - the voidInit ()//Initialize - { -memset (Land,inf,sizeof(land)); -memset (Dis,inf,sizeof(DIS)); +memset (Flag,0,sizeof(flag)); - } + A voidDijkstra () at { -dis[1]=0; - for(i=1; i<n;i++)//Traverse - { - intm=inf,x; - for(j=1; j<=n;j++) in { - if(!flag[j]&&dis[j]<M) to { +m=Dis[j]; -x=J; the } * } $flag[x]=1;//MarkPanax Notoginseng for(k=1; k<=n;k++)//Maintenance -Dis[k]=min (dis[k],dis[x]+land[x][k]); the } +cout<<dis[n]<<Endl; A } the + intMain () - { $ while(cin>>t>>N) $ { - init (); - while(t--) the { -Cin>>a>>b>>C;Wuyi if(LAND[A][B]>C)//records only the shortest theland[a][b]=land[b][a]=C; - } Wu Dijkstra (); - } About return 0; $}
View Code
2016HUAS_ACM Summer Camp 3c-til the cows Come Home