HDU 1217 (Arbitrage)

Analyzing the product to have a path weight ring is greater than 1, SPFA algorithm .

#include <iostream>
#include <cstring>
#include <string>
#include <queue>
#include <map>
using namespace std;
const int MAXN = 40;

bool vis[MAXN]; //访问情况
double dist[MAXN]; //路径权值最大乘积
double rate[MAXN][MAXN]; //汇率

//SPFA算法
void SPFA(int s, int n)
{
	queue<int> q;
	vis[s] = 1;
	dist[s] = 1.0;
	q.push(s);
	int now;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		vis[now] = 0;
		for (int i = 1; i <= n; i++)
		{
			if (dist[i] < dist[now] * rate[now][i])
			{
				if (!vis[i])
					q.push(i);
				vis[i] = 1;
				dist[i] = dist[now] * rate[now][i];
				if (dist[s] > 1)
					return;
			}
		}
	}
}

int main()
{
	int n, m;
	int cas = 1; //测试用例组数
	string s1, s2; //货币名
	double val; //汇率
	map<string, int> mp; //货币名-编号
	while (cin >> n)
	{
		if (n == 0)
			break;
		mp.clear();
		memset(vis, 0, sizeof(vis));
		memset(rate, 0, sizeof(rate));
		memset(dist, 0, sizeof(dist));
		for (int i = 1; i <= n; i++)
		{
			cin >> s1;
			mp[s1] = i;
		}
		cin >> m;
		for (int i = 0; i < m; ++i)
		{
			cin >> s1 >> val >> s2;
			rate[mp[s1]][mp[s2]] = val;
		}
		SPFA(1, n);
		if (dist[1] > 1)
			cout << "Case " << cas++ << ": " << "Yes" << endl;
		else
			cout << "Case " << cas++ << ": " << "No" << endl;
	}
	return 0;
}

Keep up.

Published 138 original articles · won praise 1 · views 6993

Guess you like

Origin blog.csdn.net/Intelligence1028/article/details/104649880