P5304 [GXOI/GZOI2019]旅行者 (dijkstra染色)

· · 题解

P5304 [GXOI/GZOI2019]旅行者

get到了新技能~~~(但本质上就只是在跑最短路时记了个father)

代码中的 dis1 ,dis2 就是上文中的 g_i ,f_i

#include<bits/stdc++.h>
#define ll long long
using namespace std;
namespace FGF
{
    int n,m,K;
    const int N=5e5+5;
    struct edg{
        int to,nxt,w;
    }e[N]; 
    int cnt,head[N],col[2][N],fro[N],to[N],w[N],a[N];
    ll dis[2][N];
    bool vis[N];
    struct Node{
        int v;ll w;
        Node(){}
        Node(int _v,ll _w):v(_v),w(_w){};
    };
    bool operator <(Node x,Node y)
    {
        return x.w>y.w;
    }
    priority_queue<Node> q;
    void add(int u,int v,int w)
    {
        cnt++;
        e[cnt].to=v;
        e[cnt].nxt=head[u];
        head[u]=cnt;
        e[cnt].w=w;
    }
    void diji(int o)
    {
        memset(dis[o],0x3f,sizeof(dis[o]));
        memset(vis,0,sizeof(vis));
        for(int i=1;i<=K;i++)
            dis[o][a[i]]=0,col[o][a[i]]=a[i],q.push(Node(a[i],0));
        while(q.size())
        {
            int u=q.top().v;q.pop();
            if(vis[u])continue;
            vis[u]=1;
            for(int i=head[u];i;i=e[i].nxt)
            {
                int v=e[i].to;
                if(dis[o][v]>dis[o][u]+e[i].w)
                {
                    dis[o][v]=dis[o][u]+e[i].w;
                    col[o][v]=col[o][u];
                    q.push(Node(v,dis[o][v]));
                }
            }
        }
    }
    void work()
    {
        int T;
        scanf("%d",&T);
        while(T--)
        {
            cnt=0;
            memset(head,0,sizeof(head));
            scanf("%d%d%d",&n,&m,&K);
            for(int i=1;i<=m;i++)
            {
                scanf("%d%d%d",&fro[i],&to[i],&w[i]);
                if(fro[i]^to[i])add(fro[i],to[i],w[i]);
            }
            for(int i=1;i<=K;i++)
                scanf("%d",&a[i]);
            diji(0);
            cnt=0;memset(head,0,sizeof(head));
            for(int i=1;i<=m;i++)
                if(fro[i]^to[i])add(to[i],fro[i],w[i]);
            diji(1);
            ll ans=0x3f3f3f3f3f3f3f3f;
            for(int i=1;i<=m;i++)
                if(col[0][fro[i]]&&col[1][to[i]]&&(col[0][fro[i]]^col[1][to[i]]))
                    ans=min(ans,dis[0][fro[i]]+dis[1][to[i]]+w[i]);
            printf("%lld\n",ans); 
        }
    }
}
int main()
{
    FGF::work();
    return 0;
}