Codeforces 707B Bakery(最短路)

这题是个水题,构建一个超级原点,把非仓库点全部连上去,然后权值为0,从超级原点出发,走一遍最短路,然后遍历仓库点,输出最小路径,唯一的注意点就是权值L会超int范围,所以要用long long。

//
//  main.cpp
//  Richard
//
//  Created by 邵金杰 on 16/8/21.
//  Copyright © 2016年 邵金杰. All rights reserved.
//

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
typedef long long LL;
const LL maxn=100000+5;
const LL INF=90000000000000;
LL flag[maxn],vis[maxn];
LL n,m,k;
struct edge{
    LL v,w;
    edge(LL v,LL w): v(v),w(w) {}
    bool operator < (const edge &e) const {
        return w>e.w;
    }
};
vector<vector<edge> > G(maxn);
vector<LL> ve;
void dijkstra()
{
    memset(vis,0,sizeof(vis));
    edge p(0,0);
    priority_queue<edge> pq;
    pq.push(p);
    LL cnt=0;
    while(!pq.empty())
    {
        p=pq.top();
        pq.pop();
        if(vis[p.v]) continue;
        vis[p.v]=1;
        if(flag[p.v]) {ve.push_back(p.w);cnt++;}
        if(cnt==k) break;
        for(int i=0;i<G[p.v].size();i++)
        {
            edge q(0,0);
            q.v=G[p.v][i].v;
            if(vis[q.v]) continue;
            q.w=p.w+G[p.v][i].w;
            pq.push(q);
        }
    }
}
int main()
{
    while(scanf("%I64d%I64d%I64d",&n,&m,&k)!=EOF)
    {
        for(int i=0;i<=n;i++) G[i].clear();
        ve.clear();
        memset(flag,0,sizeof(flag));
        LL u,v,w;
        for(int i=0;i<m;i++)
        {
            scanf("%I64d%I64d%I64d",&u,&v,&w);
            G[u].push_back(edge(v,w));
            G[v].push_back(edge(u,w));
        }
        for(int i=0;i<k;i++)
        {
            scanf("%I64d",&u);
            flag[u]=1;
        }
        for(int i=1;i<=n;i++)
        {
            if(!flag[i]) G[0].push_back(edge(i,0));
        }
        dijkstra();
        LL l=INF;
        for(int i=0;i<ve.size();i++)
        {
            l=min(l,ve[i]);
        }
        if(ve.size()==0) printf("-1\n");
        else printf("%I64d\n",l);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值