poj 2240 Arbitrage

本文介绍了一个基于Bellman算法实现货币套利判断的程序设计案例。该案例通过输入多个货币之间的兑换率,使用Bellman算法来检测是否存在盈利的货币转换循环。代码详细展示了如何构建搜索映射、填充交易矩阵,并实现Bellman算法进行套利机会检测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近做题总是错,要改几次才过。这是很难得的一个1a了。

bellman算法,和之前做过的1860类似,一个类型。

/*
POJ: 2240 Arbitrage
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>

using namespace std;

const int M = 40;

map<string, int> search_map;
double deal_map[M][M];
int n, m;
double dis[M];

bool bellman()
{
    for(int i = 2; i <= n; i++) {
        dis[i] = .0;
    }
    dis[1] = 1.0;
    
    for(int i = 0; i < n - 1; i++) {
        for(int j = 1; j <= n; j++) {
            for(int k = 1; k <= n; k++) {
                if(dis[j] < dis[k] * deal_map[k][j])
                    dis[j] = dis[k] * deal_map[k][j];
            }
        }
    }
    
    for(int j = 1; j <= n; j++) {
        for(int k = 1; k <= n; k++) {
            if(dis[j] < dis[k] * deal_map[k][j])
                return true;
        }
    }  
    return false;
}
int main()
{
    //freopen("data.in", "rb", stdin);
    int ans = 1;
    while(scanf("%d", &n) != EOF && n != 0) {
        search_map.clear();
        
        for(int i = 1; i <= n; i++) {
            string str;
            cin >> str;
            search_map.insert(make_pair(str, i));
        }
       
        for(int i = 0; i <= n; i++) {
            for(int j = 0; j <= n; j++)
                deal_map[i][j] = .0;
        }
       
        scanf("%d", &m);
        for(int i = 0; i < m; i++) {
            string str1, str2;
            double rate;
            cin >> str1 >> rate >> str2;
            deal_map[search_map[str1]][search_map[str2]] = rate;
        }
        
        if(bellman()) {
            printf("Case %d: Yes\n", ans++);
        }
        else {
            printf("Case %d: No\n", ans++);
        }
    }
    
    return 0;
}
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值