nyoj Arbitrage (Bellman-Ford)

跟天下第一挺像的

 1 void Bellman(int v0)
 2 {
 3     int i, k;
 4     for (int i = 0; i < n; ++i) {
 5         dist[i] = INF, path[i] = -1;
 6     }
 7     dist[v0] = 0;
 8     for (k = 1; k < n; ++k) {
 9         for (i = 0; i < m; ++i) {
10             if (dist[edges[i].u] != INF && edges[i].w + dist[edges[i].u] < dist[edges[i].v]) {
11                 dist[edges[i].v] = edges[i].w + dist[edges[i].u];
12                 path[edges[i].v] = edges[i].u;
13             }
14         }
15     }
16 }
17 
18 //判断是否存在从原点可达的负权值回路
19 for (i = 0; i < m; ++i) {
20     if (dist[edges[i].u] != INF && edges[i].w + dist[edges[i].u] < dist[edges[i].v])
21         return 0;
22 }
23 return 1;
Bellman

 该算法还可以求最长路径

Bellman-Ford 判断环 + 最大路径值是否大于1

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<string>
 6 #include<queue>
 7 #include<algorithm>
 8 #include<map>
 9 #include<iomanip>
10 #include<climits>
11 #include<string.h>
12 #include<cmath>
13 #include<stdlib.h>
14 #include<vector>
15 #include<set>
16 #define INF 1e7
17 #define MAXN 100010
18 #define maxn 50
19 #define maxm 1000
20 #define Mod 1000007
21 using namespace std;
22 typedef long long LL;
23 
24 struct exchange{
25     int ci, cj;
26     double cij;
27 }ex[maxm];
28 int i, j, k;
29 int n, m;
30 string name[maxn], a, b;
31 double x, maxdist[maxn];
32 bool flag;
33 int kase = 0;
34 
35 int readkase()
36 {
37     cin >> n;
38     if (n == 0) return 0;
39     for (i = 0; i < n; ++i)
40         cin >> name[i];
41     cin >> m;
42     for (i = 0; i < m; ++i) {
43         cin >> a >> x >> b;
44         for (j = 0; a != name[j]; ++j);
45         for (k = 0; b != name[k]; ++k);
46         ex[i].ci = j, ex[i].cj = k, ex[i].cij = x;
47     }
48     return 1;
49 }
50 
51 void Bellman(int v0)
52 {
53     flag = false;
54     memset(maxdist,0,sizeof(maxdist));
55     maxdist[v0] = 1;
56     for (k = 1; k <= n; ++k) {   //从maxdist(0)递推到maxdist(n)
57         for (i = 0; i < m; ++i) {//判断加入每条边是否能是最大距离增大
58             if (maxdist[ex[i].ci] * ex[i].cij > maxdist[ex[i].cj])
59                 maxdist[ex[i].cj] = maxdist[ex[i].ci] * ex[i].cij;
60         }
61     }
62     if (maxdist[v0] > 1.0) flag = true;
63 }
64 
65 int main()
66 {
67     while (readkase()) {
68         for (int i = 0; i < n; ++i) {
69             Bellman(i);
70             if (flag) break;
71         }
72         if (flag) printf("Case %d: Yes\n",++kase);
73         else printf("Case %d: No\n", ++kase);
74     }
75     return 0;
76 }

 

posted @ 2015-03-14 16:42  UsedRose  阅读(145)  评论(0编辑  收藏  举报