最短路,bellman
View Code
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
#define inf 0x3f3f3f3f
#define maxn 100
#define maxm 10000
#define eps 10e-9
int n, m, pre[maxn], edge[maxm][2];
double d[maxm];
double dist[maxn];
int dblcmp(double a, double b)
{
if (abs(a - b) < eps)
return 0;
if (a + eps < b)
return -1;
return 1;
}
int relax(int u, int v, double c)
{
if (dblcmp(dist[v], dist[u] * c) < 0)
{
dist[v] = dist[u] * c;
pre[v] = u;
return 1;
}
return 0;
}
int bellman(int src)
{
int i, j;
for (i = 0; i < n; i++)
{
dist[i] = 0;
pre[i] = -1;
}
dist[src] = 1;
bool flag;
for (i = 1; i < n; i++)
{
flag = false;
for (j = 0; j < m * 2; ++j)
{
if (1 == relax(edge[j][0], edge[j][1], d[j]))
flag = true;
}
if (!flag)
break;
}
for (j = 0; j < m; ++j)
{
if (1 == relax(edge[j][0], edge[j][1], d[j]))
return 0;
}
return 1;
}
void input()
{
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
scanf("%d%d%lf", &edge[i * 2][0], &edge[i * 2][1], &d[i * 2]);
edge[i * 2][1]--;
edge[i * 2][0]--;
edge[i * 2 + 1][0] = edge[i * 2][1];
edge[i * 2 + 1][1] = edge[i * 2][0];
d[i * 2 + 1] = d[i * 2];
d[i * 2 + 1] /= 100;
d[i * 2] /= 100;
}
}
int main()
{
//freopen("t.txt", "r", stdin);
while (scanf("%d", &n), n)
{
input();
bellman(0);
printf("%.6f percent\n", dist[n - 1] * 100);
}
return 0;
}