poj2240 Arbitrage 图论,Floyd变形

来源:互联网 发布:硕鼠mac版 编辑:程序博客网 时间:2024/06/05 05:17

题目链接:http://poj.org/problem?id=2240

题目大意:有一种套利交易,利用各种货币之间的兑换时的汇率,经过一系列的兑换,最终获利。题目意思很简单,我都看懂了。。。就不废话了

思路:抽象为一个以货币为点,以汇率为边的有向图。初始时每种货币与自身的兑换汇率是1,不能兑换的货币之间汇率设为0。问题就变成了,这个有向图中是不是存在一个回路,这个回路中各个边的权值相乘结果大于1,如果存在这样一个回路,则说明能够进行这种套利交易。

        使用Floyd算法的变形形式,改变松弛操作就行,具体看代码

///2014.7.20///poj2240//Accepted  776K    875MS   G++ 1407B   2014-07-20 12:02:16#include <iostream>#include <cstdio>#include <algorithm>#include <map>#include <string>using namespace std;int n;double dist[40][40];int cases = 0;void init(){    for(int i=0 ; i<n ; i++){        for(int j=0 ; j<n ; j++){            if( i==j )                dist[i][j] = 1;            else                dist[i][j] = 0;        }    }    map<string,int> name;    for(int i=0 ; i<n ; i++){        string nname;        cin>>nname;        name[nname] = i;    }    int m;    cin>>m;    for(int i=0 ; i<m ; i++){        string a,b;        double t;        cin>>a>>t>>b;        dist[ name[a] ][ name[b] ] = t;    }}void floyd(){    for(int k=0 ; k<n ; k++){        for(int i=0 ; i<n ; i++){            for(int j=0 ; j<n ; j++){                if( dist[i][k]*dist[k][j] > dist[i][j] ){                    dist[i][j] = dist[i][k]*dist[k][j];                }            }        }    }}void output(){    cout<<"Case "<<cases<<": ";    bool arbitrage = false;    for(int i=0 ; i<n ; i++){        if( dist[i][i]>1 )            arbitrage = true;    }    if( arbitrage )        cout<<"Yes"<<endl;    else        cout<<"No"<<endl;}int main(){    while( cin>>n && n ){        cases ++;        init();        floyd();        output();    }    return 0;}


0 0