hdu 4318 Power transmission

本文介绍了一种特殊的最短路径算法实现,通过取对数的方法来处理边权为概率的问题,适用于寻找从起点到终点的最大成功概率路径。算法采用SPFA(Shortest Path Faster Algorithm)进行求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

取对数最短路

#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<cmath>
#include<cassert>
#include<cstring>
#include<iomanip>
using namespace std;

#ifdef _WIN32
typedef __int64 i64;
#define out64 "%I64d\n"
#define in64 "%I64d"
#else
typedef long long i64;
#define out64 "%lld\n"
#define in64 "%lld"
#endif
/************ for topcoder by zz1215 *******************/
#define FOR(i,a,b)      for( int i = (a) ; i <= (b) ; i ++)
#define FFF(i,a)        for( int i = 0 ; i < (a) ; i ++)
#define FFD(i,a,b)      for( int i = (a) ; i >= (b) ; i --)
#define S64(a)          scanf(in64,&a)
#define SS(a)           scanf("%d",&a)
#define LL(a)           ((a)<<1)
#define RR(a)           (((a)<<1)+1)
#define pb              push_back
#define CL(Q)           while(!Q.empty())Q.pop()
#define MM(name,what)   memset(name,what,sizeof(name))
#define read            freopen("in.txt","r",stdin)
#define write           freopen("out.txt","w",stdout)

const int inf = 0x3f3f3f3f;
const i64 inf64 = 0x3f3f3f3f3f3f3f3fLL;
const double oo = 10e9;
const double eps = 10e-9;
const double pi = acos(-1.0);
const int maxn = 50011;

int n;
struct zz
{
	int from;	
	int to;
	double c;
}zx;

vector<zz>g[maxn];
double way[maxn];
bool inq[maxn];
int s,t;
double w;

void spfa()
{
	for(int i=1;i<=n;i++)
	{
		way[i]=-oo;
		inq[i]=false;
	}	
	deque<int>q;
	q.clear();
	q.push_back(s);
	inq[s]=true;
	way[s]=0.0;
	int now,to;
	double temp;
	while(!q.empty())
	{
		now = q.front();
		q.pop_front();
		for(int i=0;i<g[now].size();i++)
		{	
			to = g[now][i].to;
			temp = g[now][i].c + way[now];
			if(temp > way[to] + eps)
			{
				way[to]=temp;
				if(!inq[to])
				{
					inq[to]=true;
					if(!q.empty() && temp > way[q[0]])
					{
						q.push_front(to);
					}
					else	
					{
						q.push_back(to);
					}
				}
			}
		}		
		inq[now]=false;
	}
	return ;
}

int main()
{
	while(cin>>n)
	{
		int k;
		for(int i=1;i<=n;i++)
		{
			g[i].clear();
		}
		for(int i=1;i<=n;i++)
		{	
			SS(k);
			zx.from = i;
			for(int j=1;j<=k;j++)
			{
				SS(zx.to);
				scanf("%lf",&zx.c);
				zx.c = 100.0 - zx.c;		
				zx.c/=100.0;	
				zx.c = log(zx.c);
				g[zx.from].pb(zx);
			}
		}			
		cin>>s>>t>>w;
		spfa();
		if(abs(way[t]-oo)<eps)
		{
			cout<<"IMPOSSIBLE!"<<endl;
		}
		else
		{
			printf("%.2lf\n",w-exp(way[t])*w);	
		}
	}
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值