#include <stdio.h>
#include <queue>
#include <iostream>
#include <map>
#include <string>
using namespace std;
#define INF 0xfffff //因为为了辨别是否有负权,所以INF不能开太大
#define MAX 1100
float dist[MAX], pre[MAX], path[MAX][MAX];
bool sign[MAX];
void initialize(int n) //初始化
{
for(int i=1; i<=n; i++)
{
{
//pre[i] = 0;
dist[i] = 0; //将距离开始全变为最大
sign[i] = false;
}
for(int j=1; j<=n; j++)
if(i == j) path[i][j] = 1.0; //图初始
else path[i][j] = 0;
}
}
bool spfa(int n, int start) //无法计算负权
{
/* for (int i=1; i<=n; ++i)//初始化
{
dist[i] = INF;
sign[i] = false;
}*/
queue<int> Q;
dist[start] = 1.0;
sign[start] = true;
Q.push(start);
while (!Q.empty())
{
int temp = Q.front();
Q.pop();
sign[temp] = false;
for (int i=1; i<=n; ++i)
{
if (dist[temp] * path[temp][i] > dist[i])//存在负权的话,就需要创建一个COUNT数组,当某点的入队次数超过V(顶点数)返回。
{
dist[i] = dist[temp] * path[temp][i];
if (!sign[i])
{
Q.push(i);
sign[i] = true;
}
if( dist[start] > 1.0)
return true;
}
}
}
return false;
}
void input(int line)
{
map<string, int>list;
for(int i=1; i<=line; i++)
{
string temp; cin >> temp;
list[temp] = i;
}
int count;
scanf("%d", &count);
string a, b;
float weight;
for(int i=0; i<count; i++)
{
cin >> a >> weight >> b;
//if(path[list[a]][list[b]] > weight) //有多条路,保存最短的那条
{
path[list[a]][list[b]] = weight;
//path[list[b]][list[a]] = weight; //无向图双向
}
}
}
int main()
{
int n, T=0;
while(~scanf("%d", &n) && n )
{
initialize(n);
input(n);
int flag =1;
for(int i=1; i<=n; i++)
{
if(spfa(n, i) )
{printf("Case %d: Yes\n", ++T); flag = 0; break;}
}
if(flag) {printf("Case %d: No\n", ++T); }
}
return 0;
}
附件列表
时间: 2024-10-12 15:58:17