- Test instructions: Don't want to say, this question meaning, ambiguous =-=
- The Dijkstra algorithm cannot calculate a graph with negative edges, because a graph with negative edges is the precondition of disrupting the Dijkstra algorithm, and the distance from the current priority queue is the minimum distance from the starting point, because if there is a negative edge, the distance will be smaller. Besides, the Bellman-ford algorithm and the Floyd-warshall algorithm can calculate the graphs with negative edges and determine whether there are negative loops.
- Floyd-warshall algorithm: The algorithm uses the idea of dynamic planning to find the shortest distance between any two points. Order: D[k][i][j] for the shortest path can include all vertices from 0 to K when I to j minimum distance, then do a return to all vertices from 0 to k-1 to select the most short-circuit, and consider whether to include the K-vertex in the two cases of the smallest, namely: d [k][I][J]=mINd [k?1][I][J],d [k?1][I][k]+d [k?1][k][J] 。 This algorithm has a triple loop implementation complexity is O(|V | 3 ) 。
#include <iostream>#include <algorithm>#include <cstdio>using namespace STD;intd[311][311], N, M, par[311], rank[311], team[311];voidGet_team (void) { for(inti =0; I < n; i++) { for(intj =0; J < N; J + +) {if(i = = j) D[i][j] =0;ElseD[I][J] =0x3fffff; } } for(inti =0; I < m; i++) {intXscanf("%d", &x); for(intj =0; J < X; J + +) {scanf("%d", &team[j]); } for(intj =0; J < X; J + +) { for(intK = j +1; K < x; k++) {if(Team[k] = = Team[j])Continue; D[TEAM[K]-1][TEAM[J]-1] =1; D[TEAM[J]-1][TEAM[K]-1] =1; } } }}voidFloyd_warshall (void) { for(inti =0; I < n; i++) for(intj =0; J < N; J + +) for(intK =0; K < n; k++) D[j][k] = min (D[j][k], d[j][i] + d[i][k]);}intAverage_max (void) {intMax =0x3fffff; for(inti =0; I < n; i++) {inttemp =0; for(intj =0; J < N; J + +) {temp + = D[i][j]; }if(Temp < max) swap (max, temp); }returnMax * -/(N-1);}intMainvoid) { while(~scanf("%d%d", &n, &m)) {Get_team (); Floyd_warshall ();printf("%d\n",(int) Average_max ()); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
POJ 2139 Floyd-warshall algorithm to find the shortest circuit