http://acm.hdu.edu.cn/showproblem.php?pid=1596
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
#include <cstdio> #include <cstring> #include <queue> #define MAXN 1100 using namespace std; double map[MAXN][MAXN]; int vis[MAXN];//判断是否加入队列了 int num; double low[MAXN];//存最短路径 int s, e; int M, N; void SPFA() { int i, j; queue<int> Q; memset(low, 0, sizeof(low)); memset(vis, 0, sizeof(vis)); vis[s] = 1; low[s] = 1; Q.push(s); while(!Q.empty()) { int u = Q.front(); Q.pop(); vis[u] = 0;//出队列了,不在队列就变成0 for(i = 1; i <= N; ++i) { if(low[i] < low[u] * map[u][i]) { low[i] = low[u] * map[u][i]; if(!vis[i]) { vis[i]=1; Q.push(i); } } } } if(low[e] == 0) printf("What a pity!\n"); else printf("%.3f\n",low[e]); } int main() { int u, v; double w; while(~scanf("%d", &N)) { num=0; for(int i=1 ;i <= N; ++i) { for(int j=1; j <= N; ++j) { scanf("%lf",&w); map[i][j]=w; } } scanf("%d", &M); while(M--) { scanf("%d%d", &s, &e); SPFA(); } } return 0; }
Dijkstra
#include<stdio.h> #include<string.h> double map[1010][1010]; double dis[1010]; bool used[1010]; int n; int i,j; void dijkstra(int u) { memset(used,0,sizeof(used)); for(i=1;i<=n;++i) dis[i]=0; int pos=u; for(i=1;i<=n;++i)//第一次给dis赋值 { dis[i]=map[u][i]; } dis[u]=1; used[u]=1; for(i=1;i<n;++i)//再找n-1个点 { double max=0; for(j=1;j<=n;++j) { if(!used[j]&&max<dis[j]) { max=dis[j]; pos=j; } } used[pos]=1; dis[pos]=max; for(j=1;j<=n;++j)//把dis数组更新,也叫松弛 { if(!used[j]&&dis[j]<map[pos][j]*dis[pos]) { dis[j]=map[pos][j]*dis[pos]; } } } } int main() { int m; double w; int u,v; while(~scanf("%d",&n)) { for(i=1;i<=n;++i) for(j=1;j<=n;++j) { scanf("%lf",&w); map[i][j]=w; } scanf("%d",&m); while(m--) { scanf("%d%d",&u,&v); dijkstra(u); if(dis[v]==0) printf("What a pity!\n"); else printf("%.3lf\n",dis[v]); } } return 0; } /* 3 1 0.5 0.5 0.5 1 0.2 0.5 0.2 1 3 1 2 2 3 1 3 */