代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 55;
int t, n, m;
double dis[N], in[N];
bool vis[N];
int head[N], tot;
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){
if(ch == '-'){
f = -1;
}
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
x = x * 10 + ch - 48;
ch = getchar();
}
return x * f;
}
struct Node{
int to, next;
double w;
}edges[N * 2];
void add(int u, int v, double w){
tot++;
edges[tot].to = v;
edges[tot].w = w;
edges[tot].next = head[u];
head[u] = tot;
}
bool spfa(double mid){
queue<int> q;
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n; i++){
dis[i] = 0;
q.push(i);
vis[i] = true;
}
while(!q.empty()){
int x = q.front();
q.pop();
vis[x] = false;
for(int i = head[x]; i; i = edges[i].next){
if(dis[x] + (edges[i].w - mid) < dis[edges[i].to]){
dis[edges[i].to] = dis[x] + (edges[i].w - mid);
in[edges[i].to] = in[x] + 1;
if(in[edges[i].to] >= n){
return true;
}
if(!vis[edges[i].to]){
vis[edges[i].to] = true;
q.push(edges[i].to);
}
}
}
}
return false;
}
int main(){
t = read();
for(int p = 1; p <= t; p++){
memset(head, 0, sizeof(head));
memset(in, 0, sizeof(in));
n = read(), m = read();
double l = 1e9, r = -1e9;
for(int i = 1; i <= m; i++){
int u, v;
double w;
u = read();
v = read();
w = read();
l = min(l, w);
r = max(r, w);
add(u, v, w);
}
l--, r++;
double tmp = r;
double eps = 1e-5;
while(l + eps < r){
double mid = (l + r) / 2.0;
if(spfa(mid)){
r = mid;
}
else{
l = mid;
}
}
if(tmp == r){
printf("Case #%d: No cycle found.", p);
}
else{
printf("Case #%d: %0.2f", p, r);
}
if(p <= t - 1){
printf("\n");
}
}
return 0;
}