题意:和poj1860差不多的题意,给n种货币和m个兑换点,问能不能通过兑换使得原来手上的钱增加
思路:Bellman-ford求正环,外加map处理输入字符串
吐槽:把Yes打成YES...WA一次...
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 100000
#define LL long long
int cas=1,T;
struct Edge
{
int from,to;
double rab;
Edge(int u,int v,double ra):from(u),to(v),rab(ra){}
};
int n,m,num;
struct Bellford
{
vector<Edge>edges;
vector<int>G[305];
bool inq[305];
double d[305];
int cnt[305];
void init()
{
for (int i = 0;i<=n;i++)
G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,double ra)
{
int mm;
edges.push_back(Edge(from,to,ra));
mm = edges.size();
G[from].push_back(mm-1);
}
bool bellman_ford(int s)
{
queue<double> q;
memset(inq,0,sizeof(inq));
memset(cnt,0,sizeof(cnt));
for (int i = 0;i<=n;i++)
d[i]=0;
d[s]=1;
inq[s]=1;
q.push(s);
while (!q.empty())
{
int u = q.front();q.pop();
inq[u]=0;
for (int i = 0;i<G[u].size();i++)
{
Edge&e = edges[G[u][i]];
if (d[e.to] < d[e.from]*e.rab)
{
d[e.to] = d[e.from]*e.rab;
if (!inq[e.to])
{
q.push(e.to);
inq[e.to]=1;
if (++cnt[e.to] > n)
return false;
}
}
}
}
return true;
}
};
map <string,int> mapp;
int main()
{
while (scanf("%d",&n) && n)
{
printf("Case %d: ",cas++);
Bellford bf;
bf.init();
mapp.clear();
for (int i = 0;i<n;i++)
{
int j = 1;
string temp;
cin >> temp;
mapp[temp]=i+1;
}
scanf("%d",&m);
for (int i = 0;i<m;i++)
{
double r;
string s1,s2;
cin >> s1 >>r >> s2;
bf.AddEdge(mapp[s1],mapp[s2],r);
}
if (!bf.bellman_ford(1))
puts("Yes");
else
puts("No");
}
//freopen("in","r",stdin);
//scanf("%d",&T);
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return 0;
}