With a road map of self-driving, you will know the length of the highway between cities and the tolls of the road to be charged. Now you need to write a program to help visitors find a shortest route between the origin and the destination. If you have several paths that are the shortest, you need to output the cheapest path.
Input format:
Input Description: The 1th line of the input data gives 4 positive integersNMSD, whereN2) is the number of cities, by the way assuming the city's number is 0~ (n? 1); m is the number of highways; S is the city number of the departure point; d is the city number of the destination. Subsequent m line, each line gives the information of a highway, respectively: City 1, City 2, highway length, charge amount, the middle with a space separate, The numbers are integers and do not exceed 500. The input guarantees the existence of the solution.
Output format:
In a row, the length of the output path and the total charge, the numbers are separated by a space, the output end can not have extra space.
Input Sample:
4 5 0 3 0 1 1 - 1 3 2 - 0 3 4 Ten 0 2 2 - 2 3 1 -
Sample output:
3 +
Floyd Code
#include <iostream>#include<string>#include<cmath>using namespacestd;#defineMAX 1e9struct { intl, S;} a[ -][ -];intMain () {intN, M, S, D,i,j,k,x,y,ll,ss; CIN>> N >> M >> S >>D; for(i =0; I < n;i++) for(j =0; J < N; J + +) { if(i = =j) {A[I][J].L=0; A[i][j].s=0; } Else{A[I][J].L=MAX; A[i][j].s=MAX; } } while(m--) {cin>> x >> y >> ll >>SS; A[X][Y].L=ll; A[Y][X].L=ll; A[y][x].s=SS; A[x][y].s=SS; } for(k =0; K < n;k++) for(i =0; I < n;i++) for(j =0; J < n;j++) if(A[I][J].L>A[I][K].L + a[k][j].l | | a[i][j].l = = A[I][K].L + A[k][j].l&&a[i][j].s>a[i][k].s +a[k][j].s) {A[I][J].L= a[i][k].l+A[K][J].L; A[i][j].s= A[i][k].s +A[k][j].s; } cout<< A[S][D].L <<" "<<A[s][d].s;}
Floyd algorithm (alas, the ladder will not learn before the game)
#include <stdio.h>#defineMAX 100000typedefstruct{ intweight; intCost ;} Graph;intn,m,s,d;graph g[ -][ -];intdis[ -];intcost[ -];intflag[ -];voidDijkstra (intv) { intMin,i,j,pos; for(i=0; i<n;i++) { if(g[v][i].weight>0) {Dis[i]=G[v][i].weight; Cost[i]=G[v][i].cost; }} Flag[v]=1; for(i=0; i<n;i++) {min=MAX; POS=v; for(j=i;j<n;j++) { if(flag[j]!=1&&dis[j]<min &&dis[j]>0) {min=Dis[j]; POS=J; }} Flag[pos]=1; for(j=0; j<n;j++) { if(flag[j]!=1&&DIS[POS]+G[POS][J].WEIGHT<DIS[J] &&g[pos][j].weight>0&&dis[j]>0) {Dis[j]=dis[pos]+G[pos][j].weight; COST[J]=cost[pos]+G[pos][j].cost; } Else if(Dis[pos]+g[pos][j].weight==dis[j] &&cost[j]>cost[pos]+g[pos][j].cost) {Cost[j]=cost[pos]+G[pos][j].cost; }}} printf ("%d%d\n", Dis[d],cost[d]); }main () {intA,b,l,c; inti,j; scanf ("%d%d%d%d",&n,&m,&s,&D); for(i=0; i<m;i++) {scanf ("%d%d%d%d",&a,&b,&l,&c); G[a][b].weight=g[b][a].weight=l; G[a][b].cost=g[b][a].cost=B; } Dijkstra (S);}
Travel Planning (self-written Floyd code + DIJ algorithm not learned)