算法题——作物杂交

发布时间 2023-03-27 15:04:52作者: HD0117

题目

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<cmath>
using namespace std;
const int N = 2010;
const int M = 200010;
int n,m;
int h[N], e[M], w[N], target[M], ne[M], idx;
int dist[N];
queue<int> q;
bool st[N];
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 x=q.front();
        q.pop();
        st[x]=false;//不在队列里就设置st[x]=true,不断地入队出队,用节点去更新距离
        for(int i=h[x]; i!=-1; i=ne[i])
        {
            int y=e[i],z=target[i];
            if(dist[z]>max(dist[x],dist[y])+max(w[x],w[y]))
            {
                dist[z]=max(dist[x],dist[y])+max(w[x],w[y]);
                if(!st[z])
                {
                    q.push(z);
                    st[z]=true;
                }
            }
        }
    }
}
int main()
{
    int k,t;
    cin>>n>>m>>k>>t;
    memset(h, -1, sizeof h);
    for(int i=1; i<=n; i++) cin>>w[i];
    memset(dist, 0x3f, sizeof(dist));
    while(m--)
    {
        int x;
        cin>>x;
        dist[x]=0;
        q.push(x);
        st[x]=true;
    }
    while(k--)
    {
        int a,b,c;
        cin>>a>>b>>c;
        add(a,b,c);
        add(b,a,c);
    }
    spfa();
    cout<<dist[t]<<endl;
    return 0;
}