P2784 化学1(chem1)- 化学合成
还是spfa,距离数组初始化为-1,松弛操作改为*就好了,一开始老是超时,后来加了一个visit数组就过了,这个重复造成的效率浪费还是蛮大的,以后都要加。
#include<bits/stdc++.h>
using namespace std;
struct node
{
double v;
int n;
node *next;
}*e[2000010];
void push(int x,int y,double z)
{
node *p=new node();
p->n=y;
p->v=z;
if(e[x]==NULL)
{
e[x]=p;
}
else
{
p->next=e[x]->next;
e[x]->next=p;
}
}
int s,t,n,m;
queue<int>q;
double d[5010];
bool vis[5010];
void spfa(int x)
{
for(int i=1;i<=n;i++)
d[i]=-11111111.0;
d[x]=1.0;
q.push(x);
vis[x]=1;
node *p;
while(!q.empty())
{
p=e[q.front()];
while(p!=NULL)
{
if(d[q.front()]*p->v>d[p->n])
{
d[p->n]=d[q.front()]*p->v;
if(!vis[p->n])
{
q.push(p->n);
vis[p->n]=1;
}
}
p=p->next;
}
vis[q.front()]=0;
q.pop();
}
}
void in(int &x)
{
char c=getchar();x=0;
while(c<'0'||c>'9')c=getchar();
while(c<='9'&&c>='0')x=x*10+c-'0',c=getchar();
}
int main()
{
cin>>n>>m>>s>>t;
int x,y;
double z;
for(int i=1;i<=m;i++)
{
in(x),in(y);
scanf("%lf",&z);
push(x,y,z);
}
spfa(s);
if(d[t]!=-11111111.0)
printf("%.4f",d[t]);
else
cout<<"orz";
return 0;
}
来源:https://www.cnblogs.com/war1111/p/7406564.html