题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1217
分析:普通的spfa 不过要注意是要向大的转换,且初始化 dis[s] 要赋一个正数代表初始的金钱数
#include <cstring>
#include <iostream>
#include <queue>
#include <cstdio>
#include <vector>
#include <map>
#include <cstring>
#include <string>
using namespace std;
#define maxn 1050
int N,M;
double G[maxn][maxn];
double dis[maxn];
int inq[maxn];
int times[maxn];
map<string,int>ma;
void init()
{
memset(inq,0,sizeof(inq));
memset(times,0,sizeof(times));
for(int i = 0 ; i <= N ; ++i)dis[i] = -1;
for(int i = 0 ; i <= N ; ++i)
for( int j = 0 ; j <= N ; ++j)
G[i][j] = 0;
}
void read()
{
string st,str;
for(int i = 1 ; i <= N ; ++i)
{
cin >> st;
ma[st] = i;
}
cin >> M;
for( int i = 1 ; i <= M ; ++i)
{
double a;
cin >> st >> a >> str;
G[ma[st]][ma[str]] = a;
}
}
int spfa()
{
queue<int>Q;
int s = 1;
Q.push(s);
inq[s] = 1;
dis[s] = 1;//此处赋初始金钱
while(!Q.empty())
{
int u = Q.front();
Q.pop();
inq[u] = 0;
for(int i = 1 ; i <= N ; ++i)
{
if(G[u][i])
{
int v = i;
if(dis[v] < dis[u]*G[u][i] )//此处注意不同
{
dis[v] = dis[u]*G[u][i];
if( !inq[v] )
{
Q.push(v);
inq[v] = 1;
times[v]++;
if( times[v] > N )
return 1;
}
}
}
}
}
return 0;
}
int main()
{
int k = 1;
while(cin >> N && N)
{
init();
read();
printf("Case %d: ",k++);
if( spfa() ) cout << "Yes" << endl;
else cout << "No" << endl;
}
}