pku 2240 Arbitrage 第一周训练——最短路

http://poj.org/problem?id=2240

刚开始看到题目时,看到数据量很小,就想到了搜索,搜索所有的环然后将边的权值相乘看是否大存在于1.0的环。。结果果断的TLE无语。。。

最后看了看Discuss floyd1A

View Code
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#define maxn 34
#define eps 1e-8
using namespace std;
char str[maxn][maxn];
double map[maxn][maxn];
bool vt[maxn];
int ans,tmp;
int n,m;
void init()
{
int i,j;
for (i = 0; i <= n; ++i)
{
for (j = 0; j <= n; ++j)
{

map[i][j] = 0;//初始化为0,因为求的是最大值
}
}
}
void floyd()
{
int i,j,k;
for (k = 0; k < n; ++k)
{
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
if (map[i][k]*map[k][j] - map[i][j] > eps )//这里就不要加i!=j的判断了,因为我们要的就是这个值
map[i][j] = map[i][k]*map[k][j];
}
}
}
}
int getpos(char *t)
{
for (int i = 0; i < n; ++i)
{
if (strcmp(t,str[i]) == 0)
return i;
}
return -1;
}
int main()
{
int i,cas = 1;
char s1[maxn],s2[maxn];
double val;
while (~scanf("%d",&n))
{
if (!n) break;
init();
for (i = 0; i < n; ++i)
scanf("%s",str[i]);
scanf("%d",&m);
for (i = 0; i < m; ++i)
{
scanf("%s%lf%s",s1,&val,s2);
int pos1 = getpos(s1);
int pos2 = getpos(s2);
//printf("%d %d\n",pos1,pos2);
map[pos1][pos2] = val;
}
floyd();
/*for (i =0; i < n; ++i)
{
printf(">>>%.2lf\n",map[i][i]);
}
*/
bool flag = false;
for (i = 0; i < n; ++i)
{
if (map[i][i] > 1.0)
{
flag = true;
break;
}
}
if (flag) printf("Case %d: Yes\n",cas++);
else printf("Case %d: No\n",cas++);
}
return 0;
}



你可能感兴趣的:(最短路)