SPFA+0/1分数规划。
CODE:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define MAXN 1010
#define INF 0X3F3F3F3F
#define eps 1e-7
struct Edge
{
int v, next;
double w;
}edge[MAXN*5];
double d[MAXN], num[MAXN];
int first[MAXN];
int n, m, cnt;
void init()
{
cnt = 0;
memset(first, -1, sizeof(first));
}
void read_graph(int u, int v, double w)
{
edge[cnt].v = v, edge[cnt].w = w;
edge[cnt].next = first[u], first[u] = cnt++;
}
int spfa(int src, double mid)
{
queue<int> q;
bool inq[MAXN] = {0};
int ct[MAXN] = {0};
for(int i = 1; i <= n; i++) d[i] = (i == src)?0:INF;
q.push(src);
while(!q.empty())
{
int x = q.front(); q.pop();
inq[x] = 0, ct[x]++;
if(ct[x] >= n) return 0; //存在负环
for(int e = first[x]; e != -1; e = edge[e].next)
{
int v = edge[e].v;
double w = -num[v] + mid*edge[e].w;
if(d[v] > d[x] + w)
{
d[v] = d[x] + w;
if(!inq[v])
{
inq[v] = 1;
q.push(v);
}
}
}
}
return 1;
}
double BSearch()
{
double x = 0, y = 100.0, ans;
while((y-x) > eps)
{
double mid = x+(y-x)/2;
if(spfa(1, mid))
{
ans = mid;
y = mid;
}
else x = mid;
}
return ans;
}
int main()
{
scanf("%d%d", &n, &m);
init();
for(int i = 1; i <= n; i++)
{
scanf("%lf", &num[i]);
}
while(m--)
{
int u, v;
double w;
scanf("%d%d%lf", &u, &v, &w);
read_graph(u, v, w);
}
double ans = BSearch();
printf("%.2lf\n", ans);
return 0;
}
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define MAXN 1010
#define INF 0X3F3F3F3F
#define eps 1e-7
struct Edge
{
int v, next;
double w;
}edge[MAXN*5];
double d[MAXN], num[MAXN];
int first[MAXN];
int n, m, cnt;
void init()
{
cnt = 0;
memset(first, -1, sizeof(first));
}
void read_graph(int u, int v, double w)
{
edge[cnt].v = v, edge[cnt].w = w;
edge[cnt].next = first[u], first[u] = cnt++;
}
int spfa(int src, double mid)
{
queue<int> q;
bool inq[MAXN] = {0};
int ct[MAXN] = {0};
for(int i = 1; i <= n; i++) d[i] = (i == src)?0:INF;
q.push(src);
while(!q.empty())
{
int x = q.front(); q.pop();
inq[x] = 0, ct[x]++;
if(ct[x] >= n) return 0; //存在负环
for(int e = first[x]; e != -1; e = edge[e].next)
{
int v = edge[e].v;
double w = -num[v] + mid*edge[e].w;
if(d[v] > d[x] + w)
{
d[v] = d[x] + w;
if(!inq[v])
{
inq[v] = 1;
q.push(v);
}
}
}
}
return 1;
}
double BSearch()
{
double x = 0, y = 100.0, ans;
while((y-x) > eps)
{
double mid = x+(y-x)/2;
if(spfa(1, mid))
{
ans = mid;
y = mid;
}
else x = mid;
}
return ans;
}
int main()
{
scanf("%d%d", &n, &m);
init();
for(int i = 1; i <= n; i++)
{
scanf("%lf", &num[i]);
}
while(m--)
{
int u, v;
double w;
scanf("%d%d%lf", &u, &v, &w);
read_graph(u, v, w);
}
double ans = BSearch();
printf("%.2lf\n", ans);
return 0;
}