hdu 1596 find the safest road(spfa算法)
2013-07-28 16:01
567 查看
find the safest road
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4707 Accepted Submission(s): 1722
Problem Description
XX星球有很多城市,每个城市之间有一条或多条飞行通道,但是并不是所有的路都是很安全的,每一条路有一个安全系数s,s是在 0 和 1 间的实数(包括0,1),一条从u 到 v 的通道P 的安全度为Safe(P) = s(e1)*s(e2)…*s(ek) e1,e2,ek是P 上的边 ,现在8600 想出去旅游,面对这这么多的路,他想找一条最安全的路。但是8600 的数学不好,想请你帮忙 ^_^
Input
输入包括多个测试实例,每个实例包括:
第一行:n。n表示城市的个数n<=1000;
接着是一个n*n的矩阵表示两个城市之间的安全系数,(0可以理解为那两个城市之间没有直接的通道)
接着是Q个8600要旅游的路线,每行有两个数字,表示8600所在的城市和要去的城市
Output
如果86无法达到他的目的地,输出"What a pity!",
其他的输出这两个城市之间的最安全道路的安全系数,保留三位小数。
Sample Input
3
1 0.5 0.5
0.5 1 0.4
0.5 0.4 1
3
1 2
2 3
1 3
Sample Output
0.500
0.400
0.500
Author
ailyanlu
Source
HDU 2007-Spring Programming Contest - Warm Up
(1)
Recommend
8600
解析:一开始用bellman_ford算法无限超时中,很happy哈!5000ms都被我搞爆了,仔细一想这算法接近你N^4d的算法,亏自己敢用
后来想到这个算法的优化:spfa,用优先队列搞的,结果还是超时,怎么回事?想不通,可能是StL比较费时,自己手动模拟把!还超时,后来参考大神的才过~~
留个模版,以后接着研究
code:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int vis[1002],q[1000002];
double dis[1002],mp[1002][1002];
int s,e,n,m,front,rear;
void spfa()
{
int p;
while(front<rear)
{
p=q[front++];
vis[p]=0;
for(int i=1;i<=n;i++)
{
if(mp[p][i]==0||p==i) continue;
if(dis[i]<dis[p]*mp[p][i])
{
dis[i]=dis[p]*mp[p][i];
if(!vis[i])
{
vis[i]=1;
q[rear++]=i;
}
}
}
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%lf",&mp[i][j]);
scanf("%d",&m);
while(m--)
{
scanf("%d %d",&s,&e);
memset(vis,0,sizeof(vis));
memset(dis,0,sizeof(dis));
front=1;
rear=2;
vis[s]=dis[s]=1;
q[front] = s ;
spfa();
if(dis[e]!=0)
printf("%.3lf\n",dis[e]);
else
puts("What a pity!");
}
}
return 0;
}
相关文章推荐
- HDU 1596 find the safest road <SPFA算法的一个变形>
- HDU 1596 find the safest road (spfa算法)
- hdu 1596 find the safest road(最短路,模版题)
- hdu-1596-find the safest road
- HDU 1596 find the safest road
- HDU 1596——find the safest road
- hdu-1596-find the safest road(dijkstra)
- hdu 1596 find the safest road (变形SP && dij+heap)
- HDU 1596:find the safest road
- hdu 1596 find the safest road (floyd)
- HDU 1596----find the safest road
- hdu1596 find the safest road(最短路径floyd)
- HDU 1596 find the safest road 最短路
- find the safest road HDU - 1596 (spfa)
- HDU 1596 find the safest road(类最短路径)
- HDU1596 find the safest road---(最短路径dijkstra,#变形#)
- 【最短路径-Dis】hdu 1596 find the safest road
- hdu 1596 find the safest road
- hdu 1596 find the safest road(最短路)
- HDU 1596 find the safest road -- floyd