题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1596
求给定的任意两点之间的最大安全概率,概率之间是相乘的关系,所以注意初始化即可
#include<iostream> #include<stdio.h> #include<algorithm> #include<math.h> #include<string.h> #include<string> #include<stack> #include<vector> #include<map> using namespace std; #define N 1210 #define INF 0x3f3f3f3f #define met(a, b) memset(a, b, sizeof(a)) typedef long long LL; double dist[N], G[N][N]; int vis[N], n; double Dijkstra(int s, int e) { for(int i=1; i<=n; i++) dist[i] = 0; for(int i=1; i<=n; i++) dist[i] = G[s][i]; met(vis, 0); vis[s] = 1; for(int i=1; i<=n; i++) { double Max = -INF; int Index = -1; for(int j=1; j<=n; j++) { if(dist[j]>Max && !vis[j]) { Max = dist[j]; Index = j; } } if(Index == -1)break; vis[Index] = 1; for(int j=1; j<=n; j++) { if(!vis[j] && dist[j] < dist[Index]*G[Index][j]) dist[j] = dist[Index]*G[Index][j]; } } return dist[e]; } int main() { int m; while(scanf("%d", &n)!=EOF) { for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) scanf("%lf", &G[i][j]); } scanf("%d", &m); for(int i=1; i<=m; i++) { int u, v; scanf("%d %d", &u, &v); double ans = Dijkstra(u, v); if(ans == 0) puts("What a pity!"); else printf("%.3lf ", ans); } } return 0; }