Test instructions: Given a weighted graph of n-point m-bars, the loop with the smallest average weight is calculated.
Idea: Use the dichotomy method to solve, for each of the enumeration value of mid, determine the weight of each edge minus mid after the negative circle can be.
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <iostream > #include <algorithm> #include <vector> #include <map> #include <queue> #include <stack& Gt #include <string> #include <map> #include <set> #define EPS 1e-4 #define LL Long long using namespace std; const int MAXN = + 5;const int INF = 0x3f3f3f3f;//bellman-ford algorithm struct Edge {int from, to;double Dist; Edge (int u = 0, int v = 0, double d = 0): From (U), to (v), Dist (d) {}};struct bellmanford{int n, m;vector<edge> Edge S;vector<int> G[maxn];bool INQ[MAXN];d ouble d[maxn];int p[maxn];int cnt[maxn];void init (int n) {this->n = N;for (int i = 0; i < n; i++) G[i].clear (); Edges.clear ();} void Addedges (int from, int to, Int. dist) {Edges.push_back (Edge (from, to, Dist)); m = Edges.size (); G[from].push_back (m-1);} BOOL Negetivecycle () {queue<int> q;memset (inq, 0, sizeof (INQ)), memset (CNT, 0, sizeof (CNT)); for (int i = 0; i < n; i++) {D[i] = 0; Inq[0] = true; Q.push (i);} while (! Q.empty ()) {int u = q.front (); Q.pop (); Inq[u] = false;for (int i = 0; i < g[u].size (); i++) {edge& e = edges[g[u][i]];if (d[e.to]>d[u]+e.dist) {D [E.to] = D[u] + e.dist;p[e.to] = g[u][i];if (!inq[e.to]) {Q.push (e.to); inq[e.to] = True;if (++cnt[e.to] > N) return true; }}}}return false;}} Solver int N, M;bool test (double W) {for (int i = 0; i < m; i++) Solver.edges[i].dist-= W;int t = solver.negetivecycle (); for (i NT i = 0; I < m; i++) Solver.edges[i].dist + = W;return t;} int Kase;int Main () {freopen ("Input.txt", "R", stdin); int t; Cin >> T;while (t--) {cin >> n >> m;solver.i NIT (n); for (int i = 0; i < m; i++) {int u, V, d;cin >> u >> v >> d;u--; v--;solver. Addedges (U, V, d);} Double L = -10000001, R = 10000001;if (!test (R)) printf ("Case #%d:no cycle found.\n", ++kase); else {while (r-l>eps) {Dou ble M = (r+l)/2;if (Test (M)) R = M;else L = m;} printf ("Case #%d:%.2lf\n", ++kase, R);}} RetUrn 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
UVA 11090 going in cycle!! (Bellman-ford judgment Negative circle)