Topic Links:
http://poj.org/problem?id=1511
Main topic:
This topic is more difficult to understand, I read for a long time, and finally in the help of teammates to understand the test instructions, the effect is, to a starting point, from one to the other points of the shortest loop sum.
Problem Solving Ideas:
There are several error-prone solutions to this problem, and the solution is not far from AC ^_^.
1: The data range is 1<= edge number <= vertex number <=1000000, so can not use the adjacency matrix, to use the adjacency table, when the vector implementation of the dynamic application of memory.
2: To find the shortest loop from the starting point to other points, we can build two adjacency tables (a forward, a negative adjacency table), SPFA on two tables respectively.
3: Data is too large, the final result should be saved with __int64 or long long.
(This is the first time to write SPFA, but also for the first time with the vector to achieve the adjacency table, with the help of teammates have been from early in the morning until now finally solved, can take a sigh of relief to eat)
1#include <cstdio>2#include <cstring>3#include <cstdlib>4#include <vector>5#include <queue>6#include <iostream>7#include <algorithm>8 using namespacestd;9 #defineMAXN 1000005Ten #defineINF 2000000000 One A structEgde - { - inte, W; theEgde (intE=0,intw=0): E (E), W (W) {};//constructor, initialize - }; - BOOLVIS[MAXN]; - __int64 DIST[MAXN], p; +vector< vector<egde> >g[2]; - + voidInit () A { at inti; - for(i=0; i<=p; i++) -Dist[i] =INF; - } - voidSPFA (intXints); - in intMain () - { to intT, Q; +scanf ("%d", &t); - while(T--) the { *scanf ("%d%d", &p, &q); $g[0].clear ();Panax Notoginsengg[0].resize (p+1); -g[1].clear (); theg[1].resize (p+1); + A the for(intI=0; i<q; i++) + { - intS, E, W; $scanf (" %d%d%d", &s, &e, &W); $g[0][s].push_back (Egde (E, W)); -g[1][e].push_back (Egde (S, W)); - } the -__int64 sum =0;WuyiSPFA (0,1); the for(intI=1; i<=p; i++) -Sum + =Dist[i]; WuSPFA (1,1); - for(intI=1; i<=p; i++) AboutSum + =Dist[i]; $printf ("%i64d\n", sum); - - } - return 0; A } + the voidSPFA (intXints) - { $ Egde PN; theQueue<egde>que; thememset (Vis,false,sizeof(Vis)); the init (); thePN.E = s, PN.W =0; -Dist[s] =0; in Que.push (PN); theVIS[PN.E] =true; the while(!que.empty ()) About { thePN =Que.front (); the Que.pop (); theVIS[PN.E] =false; + intLen =g[x][pn.e].size (); - for(intI=0; i<len; i++) the {BayiEgde p =G[x][pn.e][i]; the if(DIST[P.E] > DIST[PN.E] +P.W) the { -DIST[P.E] = dist[pn.e] +P.W; - if(!VIS[P.E]) the { theVIS[P.E] =true; the Que.push (p); the } - } the } the } the}
POJ 1511 Invitation Cards SPFA adjacency matrix