Title Link: http://poj.org/problem?id=1511
Test instructions: gives n points and n a forward edge, all points to the source point 1 back and forth the shortest possible sum (guaranteed each point can return to the source point 1)
The problem is relatively simple is the number of sides and points a bit more so you can use dijstra+ priority queue so complexity can be to V*logn
#include <iostream> #include <cstring> #include <string> #include <vector> #include <queue > #include <cstdio> #define INF 1000000000using namespace Std;const int M = 1e6 + 10;int N, M, a[m], b[m], c[m] , dis[m];struct TnT {int V, w;}; struct CMP {bool operator () (int x, int y) {return dis[x] > Dis[y]; }};vector<tnt>vc[m];bool vis[m];void dij (int s) {priority_queue<int, vector<int>, cmp>q; Memset (Vis, false, sizeof (VIS)); TnT GG; Q.push (s); Dis[s] = 0; while (!q.empty ()) {int m = q.top (); Vis[m] = true; for (int i = 0; i < vc[m].size (); i++) {GG = vc[m][i]; if (Dis[m] + GG.W < DIS[GG.V]) {DIS[GG.V] = dis[m] + gg.w; if (!VIS[GG.V]) {VIS[GG.V] = true; Q.push (GG.V); }}} q.pop (); }}int Main () {int t; TnT GG; scanf ("%d", &T); while (t--) {scanf ("%d%d", &n, &m); for (int i = 1; I <= n; i++) {vc[i].clear (); Dis[i] = inf; } for (int i = 1; I <= m; i++) {scanf ("%d%d%d", &a[i], &b[i], &c[i]); GG.V = B[i], GG.W = C[i]; Vc[a[i]].push_back (GG); } dij (1); A long long sum = 0; for (int i = 1; I <= n; i++) {sum + = (long long) dis[i]; } for (int i = 1; I <= n; i++) {vc[i].clear (); Dis[i] = inf; } for (int i = 1; I <= m; i++) {gg.v = A[i], GG.W = C[i]; Vc[b[i]].push_back (GG); } dij (1); for (int i = 1; I <= n; i++) {sum + = (long long) dis[i]; } printf ("%lld\n", sum); } return 0; }
Poj 1511 Invitation Cards (Dijstra optimization)