Test instructions: There is a starting site, from here to send n students to the rest of the N-1 site invite people to CSS, and then back to the CSS, so that the total cost is minimal. Note that you can only send one at a time, return each time can only send one, and each road is one-way.
Analysis: This is equivalent to a graph, we only need to call the SPFA algorithm two times, the first time to find out the initial site (here is 1) to the minimum cost of all other sites, and then add, the second time the diagram is set up, that is, all sides reverse, and then find the initial site (here is 1) to other sites of the minimum , the second step of the graph backwards in accordance with the first method is equivalent to from all other points to the initial point of the minimum distance, because the algorithm can only find a single point to multipoint and can not find multipoint to a single point. The final result can be obtained by adding the results two times.
#include <iostream> #include <vector> #include <queue>using namespace Std;int u[1000001];int v[ 1000001];int w[1000001];bool vis[1000001];int d[1000001];int first[1000001];int Next[1000001];void InitAndInput (int n , int m)//input Figure {int i;for (i=1;i<=n;i++) first[i]=-1;for (i=0;i<m;i++) next[i]=-1;for (i=0;i<m;i++) {cin>> u[i]>>v[i]>>w[i]; Next[i]=first[u[i]];first[u[i]]=i;}} void Inversebulid (int n,int m)//Reverse build diagram {int i;for (i=1;i<=n;i++) first[i]=-1;for (i=0;i<m;i++) next[i]=-1;for (i=0; i<m;i++) {next[i]=first[v[i]];first[v[i]]=i;}} void SPFA (int n,int s,bool flag)//flag Indicates whether the reverse-established diagram is currently being processed or the beginning of the graph, false reverse, true starts {queue<int> q;int i,x,y;for (i=1;i& lt;=n;i++) vis[i]=false;for (i=1;i<=n;i++) d[i]= (i==s) 0:0x7fffffff; Initialize yourself to 0, others to yourself equivalent to infinity Q.push (s), while (!q.empty ()) {X=q.front (); Q.pop (); Vis[x]=false;for (i=first[x];i!=-1;i= Next[i]) {y=flag?v[i]:u[i];if (D[y]>d[x]+w[i]) {d[y]=d[x]+w[i];if (!vis[y]) {vis[y]=true; Q.push (y);}}}} int main () {int p,q, N,sum,i;cin>>n;while (n--) {sum=0;cin>>p>>q;initandinput (p,q); SPFA (P,1,true); To find the minimum and for (i=2;i<=p;i++) sum+=d[i];inversebulid (P,Q); Reverse build SPFA (P,1,false); Find the minimum and for (i=2;i<=p;i++) Sum+=d[i];cout<<sum<<endl in reverse;} return 0; }
HDU ACM 1535 Invitation Cards single point to multi-source shortest path->SPFA algorithm