Uva 11090 - Going in Cycle!! (判负圈+二分)
题目链接 https://vjudge.net/problem/UVA-11090
【题意】
给定一个n个点,m条边的加权有向图,求平均权值最小的回路,对于每组数据输出最小平均值,如果无解输出“No cycle found.”
【思路】
可以用二分来找答案,对于一个猜测值mid,判断图中是否存在平均值小于mid的回路,假设存在这样的一条回路,由k条边构成,那么w1+w2+…+wk < k*mid,移项后可得到(w1-mid)+(w2-mid)+…+(wk-mid)<0,即把所有边的权值都减去mid之后图中会有负圈存在,所以我们可以根据这一点利用BellmanFord算法来判断是否存在平均值小于mid的回路,注意要把权值的类型改为double型
#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 55;
const double eps = 1e-3;
struct Edge {
int from, to;
double dist;
Edge(int f, int t, double d) :from(f), to(t), dist(d) {}
};
struct BellmanFord {
int n, m;
vector<Edge> edges;
vector<int> g[maxn];
bool inq[maxn];
double 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 add(int from, int to, double dist) {
edges.push_back(Edge(from, to, dist));
m = edges.size();
g[from].push_back(m - 1);
}
bool negativeCycle() {
queue<int> que;
memset(inq, 0, sizeof(inq));
memset(cnt, 0, sizeof(cnt));
for (int i = 0; i < n; ++i) { d[i] = 0; inq[i] = true; que.push(i); }
while (!que.empty()) {
int u = que.front();
que.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]) {
que.push(e.to);
inq[e.to] = true;
if (++cnt[e.to] > n) return true;
}
}
}
}
return false;
}
};
int n, m;
double le, ri, mid;
BellmanFord solver;
bool check(double x) {
for (int i = 0; i < solver.m; ++i) {
solver.edges[i].dist -= x;
}
bool ans = solver.negativeCycle();
for (int i = 0; i < solver.m; ++i) {
solver.edges[i].dist += x;
}
return ans;
}
int main() {
int t;
scanf("%d", &t);
for (int kase = 1; kase <= t; ++kase) {
scanf("%d%d", &n, &m);
solver.init(n);
int maxc = 0;
for (int i = 0; i < m; ++i) {
int u, v, c;
scanf("%d%d%d", &u, &v, &c);
--u, --v;
solver.add(u, v, c);
maxc = max(maxc, c);
}
le = 0, ri = maxc + 1.0;
if (!check(ri)) {
printf("Case #%d: No cycle found.\n", kase);
continue;
}
while (ri - le > eps) {
mid = (le + ri) / 2;
if (check(mid)) { ri = mid; }
else { le = mid; }
}
printf("Case #%d: %.2lf\n", kase, ri);
}
return 0;
}