洛谷——P3003 [USACO10DEC]苹果交货Apple Delivery

P3003 [USACO10DEC]苹果交货Apple Delivery

 

这题没什么可说的,跑两遍单源最短路就好了

 

$Spfa$过不了,要使用堆优化的$dijkstra$

 

细节:1.必须使用优先队列+堆

2.更新方式跟$Spfa$有所不同

 

#include<bits/stdc++.h>

using namespace std;

void in(int &x){
    register char c=getchar();x=0;int f=1;
    while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}
    while(isdigit(c)){x=x*10+c-'0';c=getchar();}
    x*=f;
}

int c,p,p_b,pa_1,pa_2,head[2000005],vis[2000005],d[2000005],tot,ans;
struct node{
    int to,dis,pre;
}e[2000005];
void add(int u,int v,int w){
    e[++tot].to=v;e[tot].pre=head[u];head[u]=tot;e[tot].dis=w;
}
struct npde{
    int to,dis;
    bool operator < (const npde &x) const{
        return dis>x.dis;
    }
};
priority_queue<npde>Q; 
void spfa(int s){
    while(!Q.empty()) Q.pop();
    memset(vis,0,sizeof(vis));memset(d,0x7f,sizeof(d));
    d[s]=0;Q.push((npde){s,0});
    while(!Q.empty()){
        int u=Q.top().to;Q.pop();
        if(vis[u]) continue;
        vis[u]=1;
        for(int i=head[u],v;v=e[i].to,i;i=e[i].pre){
            if(d[v]>d[u]+e[i].dis){
                d[v]=d[u]+e[i].dis;
                Q.push((npde){v,d[v]});
            }
        }
    }
}
int main()
{
    in(c),in(p),in(p_b),in(pa_1),in(pa_2);
    for(int i=1;i<=c;i++){
        int u,v,w;
        in(u),in(v),in(w);
        add(u,v,w);add(v,u,w);
    }spfa(p_b);
    if(d[pa_1]<d[pa_2])ans+=d[pa_1],spfa(pa_1),ans+=d[pa_2];
    else ans+=d[pa_2],spfa(pa_2),ans+=d[pa_1];
    printf("%d\n",ans);
    return 0;
}

 

posted @ 2018-10-14 16:25  清风我已逝  阅读(224)  评论(0编辑  收藏  举报