[洛谷P2384]最短路

题目大意:给你一个图,要你求出其中1->n路径中乘积最小的一条路

题解:用$log_2$把乘法变成加法,然后记录每个点的前驱,最后求出答案

C++ Code:

#include<cstdio>
#include<cmath>
using namespace std;
const int mod=9987;
int n,m;
int head[1010],cnt;
struct Edge{
	int to,cost,nxt;
}e[1000010];
int q[2000010],h,t,res=1;
int tmp[1010][2]; 
bool v[1010];
double ans[1010]; 
void addE(int a,int b,int c){
	e[++cnt]=(Edge){b,c,head[a]};
	head[a]=cnt;
}
void SPFA(int rt){
	for (int i=2;i<=n;i++)ans[i]=1000000;
	q[++t]=rt;
	while (h<t){
		int x=q[++h];
		v[x]=false;
		for (int i=head[x];i;i=e[i].nxt){
			int to=e[i].to;double lg=log(e[i].cost);
			if (ans[to]>ans[x]+lg){
				ans[to]=ans[x]+lg;
				tmp[to][0]=x,tmp[to][1]=e[i].cost;
				if (!v[to]){
					v[to]=true;
					q[++t]=to;
				}
			}
		} 
	}
	for (int i=n;i!=1;i=tmp[i][0])res=(res*tmp[i][1])%mod;
	printf("%d
",res);
}
int main(){
	scanf("%d%d",&n,&m);
	for (int i=0;i<m;i++){
		int a,b,c;
		scanf("%d%d%d",&a,&b,&c);
		addE(a,b,c);
	}
	SPFA(1);
	return 0;
} 
原文地址:https://www.cnblogs.com/Memory-of-winter/p/8557742.html