3 1 0.5 0.5 0.5 1 0.4 0.5 0.4 1 3 1 2 2 3 1 3
0.500 0.400 0.500
AC-code:
Dijkstra:
#include<cstdio> #define min(a,b) (a>b?a:b) int n; float cost[1005][1005],dis[1005]; void dijkstra(int a) { int i,vis[1005]; for(i=1;i<=n;i++) { dis[i]=0; vis[i]=0; } dis[a]=1; while(1) { int v=-1; for(i=1;i<=n;i++) if(!vis[i]&&(v==-1||dis[i]>dis[v])) v=i; if(v==-1) break; vis[v]=1; for(i=1;i<=n;i++) dis[i]=min(dis[i],dis[v]*cost[v][i]); } } int main() { int q,i,j,a,b; while(~scanf("%d",&n)) { for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%f",&cost[i][j]); scanf("%d",&q); while(q--) { scanf("%d%d",&a,&b); dijkstra(a); if(dis[b]==0) printf("What a pity!\n"); else printf("%.3lf\n",dis[b]); } } return 0; }
SPFA:
#include<cstdio> #include<queue> #include<cstring> using namespace std; float vis[1005],dis[1005]; int head[1000*1000],nu; struct node { int from,to; float val; int next; }A[1000*1000]; void chan(int a,int b,float c) { node e={a,b,c,head[a]}; A[nu]=e; head[a]=nu++; } void spfa(int sx) { queue<int>q; memset(dis,0,sizeof(dis)); memset(vis,0,sizeof(vis)); q.push(sx); dis[sx]=1; vis[sx]=1; while(!q.empty()) { int u=q.front(); q.pop(); vis[u]=0; for(int i=head[u];i!=-1;i=A[i].next) { int v=A[i].to; if(dis[v]<dis[u]*A[i].val) { dis[v]=dis[u]*A[i].val; if(!vis[v]) { vis[v]=1; q.push(v); } } } } } int main() { int n,i,j,q,b,c; float a; while(~scanf("%d",&n)) { nu=0; memset(head,-1,sizeof(head)); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { scanf("%f",&a); chan(i,j,a); } scanf("%d",&q); while(q--) { scanf("%d%d",&b,&c); spfa(b); if(dis[c]==0) printf("What a pity!\n"); else printf("%.3f\n",dis[c]); } } return 0; }