P2784 化学1(chem1)- 化学合成

· · 题解

谁说不能用Dijkstra了?

堆优化dijA了 (第2个点960ms。。。)

上代码: (坑点挺多)

#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
typedef pair<double,int> kk;//注意小数*1
const int N=5005,M=2000000;
int n,m,s,t;
int head[N],tot;
double d[N];//注意小数*2
bool v[N];
struct edge{
    int nxt,ver;
    double w;//*3
}e[M*2];
void add(int x,int y,double z){
    e[++tot].ver=y,e[tot].w=z,e[tot].nxt=head[x],head[x]=tot;
}
//邻接表存图(没啥说的吧)
void dij(int st){
    for(int i=1;i<=n;i++) d[i]=-1;//都赋值成-1(未到达)
    priority_queue<kk>q;//大根堆
    d[st]=1;q.push(make_pair(1,st));
    while(q.size()){
        int x=q.top().second;q.pop();
        if(v[x]) continue;v[x]=1;
        for(int i=head[x];i;i=e[i].nxt){
            int y=e[i].ver;
            if(d[x]*e[i].w>d[y]){
                d[y]=d[x]*e[i].w;//注意题目要求(乘法)
                q.push(make_pair(d[y],y));
            }
        }
    }
}
int main ()
{
    scanf("%d%d%d%d",&n,&m,&s,&t);
    for(int i=1;i<=m;i++){
        int x,y;
        double z;//注意小数*4...
        scanf("%d%d%lf",&x,&y,&z);
        add(x,y,z);//图存起来!!
    }
    dij(s);
    if(d[t]!=-1) printf("%.4lf",d[t]);//-1说明不连通
    else printf("orz");
}