解题报告P3003 [USACO10DEC]苹果交货Apple Delivery

· · 个人记录

题目链接:P3003 [USACO10DEC]苹果交货Apple Delivery。

题目大意:给定 P 点 C 条边的正权无自环联通图,在给定三个点 B,A_1,A_2 。求从 B 出发, A_1,A_2 都要经过的条件下,走的路最短距离是多少。

解法:\text{Dijkstra} 堆优化

思路分析

注意到 A_1,A_2 间的最短路与 B 在哪无关。

显而易见,我们在任意时刻到达 A_1 (或 A_2)后,肯定会选择直接沿着最短路去往 A_2 (或 A_1)。否则走的路一定不是答案所要求的最短路。

而不论我们先到达 A_1 还是 A_2 ,我们都一定会选择 B 到这两个地方的最短路。

设 d[x,y] 表示 x 到 y 的最短路(当然 y 到 x 的最短路),于是答案就是 \min(d[B,A_1],d[B,A_2])+d[A_1,A_2] 。

解题步骤

现在思路就有了。

注意事项

AC 代码

评测记录。

#include<cstdio>
#include<cstring>
using namespace std;
namespace Qza{
    #define N 100002
    #define M 400002
    int en[N],nex[M],to[M];
    int gth[N],htg[N];
    unsigned int w[M],d1[N],d2[N];
    void swap_heap(int x,int y,unsigned int d[])
    {
        int u=htg[x],v=htg[y],t;
        gth[u]=y; gth[v]=x;
        htg[y]=u; htg[x]=v;
        t=d[x]; d[x]=d[y]; d[y]=t;
    }
    void push_up(int x,unsigned int d[])
    {
        for(int f=x>>1;d[f]>d[x]&&f;swap_heap(x,f,d),x=f,f=x>>1);
    }
    void push_down(int x,int n,unsigned int d[])
    {
        for(int l=x<<1,r=l|1;l<=n;x=l,l=x<<1,r=l|1) {
            if(d[l]>d[r] && r<=n) l=r;
            if(d[l]<d[x]) swap_heap(x,l,d);
            else break;
        }
    }
    void dijkstra(int s,int n,unsigned int d[])
    {
        int i,p,u,v;
        for(int i=1;i<=n;++i) {
            htg[i]=gth[i]=i;
        }
        memset(d+1,0x7f,n*sizeof(int));
        d[s]=0u;
        push_up(s,d);
        s=n;

        while(n>1) {
            u=htg[1];
            swap_heap(1,n,d);
            --n;
            push_down(1,n,d);

            for(p=en[u],u=gth[u];p;p=nex[p]) {
                v=gth[to[p]];
                if(d[v]>d[u]+w[p]) {
                    d[v]=d[u]+w[p];
                    push_up(v,d);
                }
            }
        }
        for(i=1;i<=s;++i) htg[i]=d[i];
        for(i=1;i<=s;++i) d[i]=htg[gth[i]];
    }
    int read()
    {
        char ch=getchar();int x=0;
        while(ch<'0' || ch>'9') ch=getchar();
        while(ch>='0'&&ch<='9') x=(x*10)+(ch^48),ch=getchar();
        return x;
    }
    void main()
    {
        int x,y,z,n,m,B,A1,A2,cnt=0;
        m=read(); n=read(); B=read(); A1=read(); A2=read();
        for(int i=1;i<=m;++i) {
            x=read(); y=read(); z=read(); 
            nex[++cnt]=en[x]; to[cnt]=y; en[x]=cnt; w[cnt]=z;
            nex[++cnt]=en[y]; to[cnt]=x; en[y]=cnt; w[cnt]=z;
        }
        dijkstra(B,n,d1);
        dijkstra(A1,n,d2);
        x=d1[A1]+d2[A2];
        y=d1[A2]+d2[A2];
        printf("%d",x<y?x:y); // 不要写成 x<y?y:y !!!
        return ;
    }
}
int main()
{
    Qza::main();
    return 0;
}