POJ2240 套汇(单源最短路径)

给定N种货币以及它们之间的一些兑换率,问是否存在套汇的可能,使某种货币的金钱经过套汇之后变得更多。

简单的单源最短路径问题,把每种货币看成一个点,点的初始值只需随便指定一个大于0的数,然后使用bellman-ford算法判定某个点的金钱是否可以无限增多,即是否存在正环。

#include 
#include 
#include 
#include 
using namespace std;

const int N = 35;
const int E = 905;
const double MAX = 999999999;

struct Edge
{
	int beg;
	int end;
	double rate;
}edge[E];
double mindis[N];
int n, e;
struct Name
{
	char str[55];
}cname[N];

bool cmp(const Name& n1, const Name& n2)
{
	return strcmp(n1.str, n2.str) < 0;
}

int bisearch(char* str)
{
	int low = 0, high = n - 1, mid;
	int t;
	while (low <= high)
	{
		mid = (low + high) >> 1;
		t = strcmp(str, cname[mid].str);
		if (t == 0) return mid;
		else if (t < 0) high = mid - 1;
		else low = mid + 1;
	}
	return -1;
}

bool relax(int pe)
{
	if (mindis[edge[pe].beg] * edge[pe].rate > mindis[edge[pe].end]) 
	{
		mindis[edge[pe].end] = mindis[edge[pe].beg] * edge[pe].rate;
		return true;
	}
	return false;
}

bool bellman_ford()
{
	bool flag;
	for (int i = 0; i < n; ++i) mindis[i] = 1.0;
	for (int i = 0; i < n - 1; ++i)
	{
		flag = false;
		for (int j = 0; j < e; ++j)
		{
			if (relax(j)) flag = true;
		}
		if (!flag) return false;
	}
	for (int i = 0; i < e; ++i)
	{
		if (relax(i)) return true;
	}
	return false;
}

int main()
{
	char sbeg[55], send[55];
	double rate;
	int T = 1;
	while (scanf("%d", &n) != EOF && n)
	{
		for (int i = 0; i < n; ++i) scanf("%s", cname[i].str);
		sort(cname, cname + n, cmp);
		scanf("%d", &e);
		for (int i = 0; i < e; ++i)
		{
			scanf("%s%lf%s", sbeg, &rate, send);
			edge[i].beg = bisearch(sbeg);
			edge[i].end = bisearch(send);
			edge[i].rate = rate;
		}
		printf("Case %d: ", T++);
		if (bellman_ford()) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}


你可能感兴趣的:(ACM解题报告)