Test the shortest path, and record the shortest path with the same length, then traverse and select the Optimal Shortest Path [cpp] # include <iostream> # include <vector> # include <queue> # include <stack> using namespace std; # define INF 0x6FFFFFFF int Cmax, n, Sp, m; typedef struct Edge {int v, dis; Edge (int _ v, int _ dis): v (_ v), dis (_ dis) {}} Edge; typedef struct Node {int c, dis;} Node; vector <Edge> edge; vector <Node> city; vector <int> allPath; vector <bool> visited; vector <int> be StPath; int minSend = INF; int minCollect = INF; vector <int> possiblePath; void FindBestPath (int u) {possiblePath. push_back (u); if (u = 0) {// find the end int send = 0; int collect = 0; for (int I = possiblePath. size ()-1; I> = 0; -- I) {int t = possiblePath [I]; if (city [t]. c> Cmax/2) collect + = city [t]. c-Cmax/2; else if (city [t]. c <Cmax/2) {collect-= (Cmax/2-city [t]. c); if (collect <0) send-= Collect, collect = 0 ;}}if (send <minSend) minSend = send, minCollect = collect, bestPath = possiblePath; else if (send = minSend & collect <minCollect) minCollect = collect, bestPath = possiblePath; return;} for (int I = 0; I <allPath [u]. size (); ++ I) {FindBestPath (allPath [u] [I]); possiblePath. pop_back () ;}} int FindMin () {int mmin = INF; int index =-1; for (int I = 0; I <= n; ++ I) {if (city [I]. dis <Mmin &&! Visited [I]) {mmin = city [I]. dis; index = I ;}} return index;} void Dijkstra (int s, int t) {allPath. clear (); allPath. resize (n + 1);/* for (int I = 0; I <= n; ++ I) allPath [I]. push_back (-1); */visited. assign (n + 1, false); for (int I = 0; I <= n; ++ I) city [I]. dis = INF; city [0]. dis = 0; while (true) {int u = FindMin (); if (u =-1) return; visited [u] = true; for (int I = 0; I <edge [u]. size (); ++ I) {int v = Edge [u] [I]. v; if (! Visited [v]) {int dis = edge [u] [I]. dis; if (city [v]. dis> city [u]. dis + dis) {allPath [v]. clear (); city [v]. dis = city [u]. dis + dis; allPath [v]. push_back (u);} else if (city [v]. dis = city [u]. dis + dis) {allPath [v]. push_back (u) ;}}} int main () {scanf ("% d", & Cmax, & n, & Sp, & m); city. clear (); city. resize (n + 1); for (int I = 1; I <= n; ++ I) {scanf ("% d", & city [I]. c); city [0]. c = Cmax/2;} edge. clear (); edge. resize (n + 1); for (int I = 0; I <m; ++ I) {int a, B, c; scanf ("% d", & a, & B, & c); edge [a]. push_back (Edge (B, c); edge [B]. push_back (Edge (a, c);} // end of input // 1. using dijkstra find all the possible solution Dijkstra (0, Sp); www.2cto.com // 2. enumerate all possible path and record the best one FindBestPath (Sp); // output the best solution printf ("% d 0", minSend); for (int I = bestPath. size ()-2; I> = 0; -- I) printf ("-> % d", bestPath [I]); printf ("% d \ n ", minCollect); return 0 ;}