POJ 2240:http://poj.org/problem?id=2240
n为 30
依然是前面的类似的货币交换问题,问能否靠这种交换货币的方法发家致富.......
预处理部分用map映射成数字,接下来就好办了。
Spfa:
#include"cstdio"
#include"iostream"
#include"cstring"
#include"algorithm"
#include"vector"
#include"cmath"
#include"queue"
#include"map"
using namespace std;
#define INF 9999999
#define inf 1009
#define loop(x,y,z) for(x=y;x<z;x++)
#define ll long long
int book[inf];
int cnt[inf];
int n,m;
double dis[inf];
struct node
{
int to;
double rate;
node(int i,double j)
{
to=i;
rate=j;
}
};
vector<node>edge[inf];
queue<int>q;
map<string,int>currency;
void setmap()
{
int i;
string t;
loop(i,0,n)
{
cin>>t;
currency[t]=i;
}
}
void init()
{
int i;
memset(book,0,sizeof book);
memset(cnt,0,sizeof cnt);
loop(i,0,n)dis[i]=-1;
dis[0]=100;
loop(i,0,n)edge[i].clear();
currency.clear();
while(!q.empty())q.pop();
}
bool spfa()
{
q.push(0);
book[0]=1;
int i;
while(!q.empty())
{
int u=q.front();
q.pop();
book[u]=0;
int len=edge[u].size();
loop(i,0,len)
{
node& e=edge[u][i];
if(dis[e.to]<dis[u]*e.rate)
{
dis[e.to]=dis[u]*e.rate;
if(!book[e.to])
{
q.push(e.to);
book[e.to]=1;
if(++cnt[e.to]>n-1)return false;
}
}
}
}
return true;
}
int main()
{
int i=1;
string a,b;
int x,y;
double c,t;
while(~scanf("%d",&n)&&n)
{
init();
setmap();
scanf("%d",&m);
while(m--)
{
cin>>a>>c>>b;
x=currency[a];
y=currency[b];
edge[x].push_back(node(y,c));
}
if(spfa())cout<<"Case "<<i++<<": No"<<endl;
else cout<<"Case "<<i++<<": Yes"<<endl;
}
return 0;
}