题意:给定若干种种子,这些种子可以杂交其他种类的种子,求某个未杂交出来的种子最少需要多少天。
分析:最难的是建图,假如a+b可以生成c,那么可以看为无向图,add(a,b,c),add(b,a,c)。
用d数组表示用其他种子生成其他类种子的最小天数,那么已经给定的种子就是0。
所以可以用spfa来做,用已知点去更新未知点。
代码
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int N = 2010,M = 200010;
int e[M],w[N],target[M],h[N],ne[M],idx;
int d[N];
bool st[N];
int n,m;
queue<int> q;
void add(int a,int b,int c)
{
e[idx]=b,target[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
void spfa()
{
while(q.size())
{
auto t=q.front();
q.pop();
st[t]=false;
for(int i=h[t];~i;i=ne[i])
{
int j=e[i],z=target[i];
if(d[z] > max(d[j],d[t]) + max(w[j],w[t]))//还未产生的种子的天数,需要其他已经被另外的种子产生的种子消耗的天数+这两种作物杂交需要的时间
{
d[z]=max(d[j],d[t])+max(w[j],w[t]);
if(!st[z])
{
q.push(z);
st[z]=true;
}
}
}
}
}
int main()
{
int k,T;
memset(h,-1,sizeof h);
scanf("%d%d%d%d",&n,&m,&k,&T);
for(int i=1;i<=n;i++) scanf("%d",&w[i]);
memset(d,0x3f,sizeof d);
while(m--)
{
int x;
scanf("%d",&x);
d[x]=0;
q.push(x);
st[x]=true;
}
while(k--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
add(b,a,c);
}
spfa();
printf("%d\n",d[T]);
return 0;
}