POJ 1860 Currency Exchange BellmanFord題解,pojbellmanford

來源:互聯網
上載者:User

POJ 1860 Currency Exchange BellmanFord題解,pojbellmanford

會建圖,然後使用標準的Bellman Ford演算法,判斷負環就解決了。

不過本題實際應用不是計算負環,而是計算最大值,也就是求出源點到所有點的最大收益值之後,然後判斷是否可以進一步增加收益,如果可以那麼證明有環可以不斷反覆走這個環,不斷增加收益,實際就是判負環的應用了。


#include <stdio.h>#include <vector>#include <string.h>#include <algorithm>#include <iostream>#include <string>#include <limits.h>#include <stack>#include <queue>#include <set>#include <map><span style="white-space:pre"></span>#include <float.h>using namespace std;const int MAX_N = 101;int N, M, Src;double V, dis[MAX_N];struct Node{int s, d;//source and destination vertexdouble w, c;//exchange rate and commission};Node gra[MAX_N<<1];bool BellmanFord(int src, int n, double val)//n: number of edges{fill(dis, dis+N+1, 0.0);dis[src] = val;for (int i = 1; i < N; i++)//標準Bellman Ford Algorithm{for (int j = 0; j < n; j++){int u = gra[j].s, v = gra[j].d;if (dis[u] != 0.0){double t = (dis[u]-gra[j].c) * gra[j].w;if (t > dis[v]) dis[v] = t;}}}for (int j = 0; j < n; j++)//判斷負環{int u = gra[j].s, v = gra[j].d;if (dis[u] != 0.0){double t = (dis[u] - gra[j].c) * gra[j].w;if (t > dis[v]) return true;}}return false;}int main(){while (scanf("%d %d %d %lf", &N, &M, &Src, &V) != EOF){int u, v, id = 0;double a, b, c, d;for (int i = 0; i < M; i++){scanf("%d %d %lf %lf %lf %lf", &u, &v, &a, &b, &c, &d);gra[id].s = u, gra[id].d = v;gra[id].w = a, gra[id].c = b;id++;gra[id].s = v, gra[id].d = u;gra[id].w = c, gra[id].c = d;id++;}if (BellmanFord(Src, id, V)) puts("YES");else puts("NO");}return 0;}






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.