#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
double a[1100][1100];
const double inf=1e-6;
int n;
void dij(int st,int ex)
{
double dis[1100];
int book[1100];
memset(book,0,sizeof(book));
for(int i=1;i<=n;i++) dis[i]=a[st][i];
for(int i=0;i<n;i++)
{
double mx=0;int pos=-1;
for(int j=1;j<=n;j++) if(dis[j]>mx&&!book[j]){mx=dis[j];pos=j;}
if(pos<0) break;
book[pos]=1;
for(int j=1;j<=n;j++)
if(!book[j]&&a[pos][j]>0&&dis[pos]*a[pos][j]>dis[j]) dis[j]=dis[pos]*a[pos][j];
}
if(dis[ex]>inf) printf("%.3lf\n",dis[ex]);
else printf("What a pity!\n");
}
void spfa(int st,int ex)
{
int vis[1100];
double dis[1100];
memset(vis,0,sizeof(vis));
memset(dis,0,sizeof(dis));
//for(int i=1;i<=n;i++) dis[i]=a[st][i]; // -Wr do`not know...
queue<int>que;
while(!que.empty()) que.pop();
que.push(st);vis[st]=1;dis[st]=1;
while(!que.empty())
{
int c=que.front();que.pop();vis[c]=0;
for(int i=1;i<=n;i++)
{
if(dis[c]*a[c][i]>dis[i])
{
dis[i]=dis[c]*a[c][i];
if(!vis[i])
{
que.push(i);
vis[i]=1;
}
}
}
}
if(dis[ex]>inf) printf("%.3lf\n",dis[ex]);
else printf("What a pity!\n");
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%lf",&a[i][j]);
int m;
scanf("%d",&m);
while(m--)
{
int st,ex;
scanf("%d%d",&st,&ex);
//dij(st,ex);
spfa(st,ex);
}
}
return 0;
}
版子,最短路
最新推荐文章于 2023-12-05 22:18:43 发布