POJ 2240 Bellman-Ford 判正圈

大致题意

已知 n 种货币部分的汇率关系,即 1 货币 ci 可以兑换 rij 货币 cj。求是否有可能通过数次兑换操作之后,得到的货币价值比原来持有货币价值更高。

Bellman-Ford 判断正圈(从顶点 s 返回 s 时权值增加)即可。如果图中不存在从 s 可达的正圈,那么最长路不会通过同一个顶点两次(即最多通过 V - 1 条边)。反之,若存在 s 可达的正圈,那么在第 V 次循环中也会更新最长路 d 的值。一开始对所有顶点初始化为 1.0,以检查出所有的正圈。

#include <cstdio>
#include <STDLIB.H>
#include <cmath>
#include <map>
#include <algorithm>
#include <iostream>
#include <string>
#define min(a,b)    (((a) < (b)) ? (a) : (b))
#define max(a,b)    (((a) > (b)) ? (a) : (b))
#define abs(x)    ((x) < 0 ? -(x) : (x))
#define INF 0x3f3f3f3f
#define eps 1e-5
#define M_PI 3.14159265358979323846
#define MAX_W 45
#define MAX_N 30
using namespace std;
struct edge{
	int from, to;
	double cost;
};
int N, M, V, E;
edge es[MAX_N * MAX_N];
double d[MAX_N];

void init(){
	map<string, int> mp;
	for(int i = 0; i < N; i++){
		string str;
		cin >> str;
		mp[str] = i;
	}
	scanf("%d", &M);
	for(int i = 0; i < M; i++){
		double v;
		string s1, s2;
		cin >> s1 >> v >> s2;
		es[i].from = mp[s1], es[i].to =mp[s2], es[i].cost = v;
	}
	V = N, E = M;
}
bool bellman_ford(){
	for(int i = 0; i < V; i++) d[i] = 1.0;
	for(int i = 0; i < V; i++){
		for(int j = 0; j < E; j++){
			edge e = es[j];
			if(d[e.to] < d[e.from] * e.cost){
				d[e.to] = d[e.from] * e.cost;
				if(i == V - 1) return true;
			}
		}
	}
	return false;
}
int main(){
	int t = 0;
	while(cin >> N && N){
		init();
		if(bellman_ford()) printf("Case %d: Yes\n", ++t);
		else printf("Case %d: No\n", ++t);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值