图专项——最短路(多源多汇)

多源多汇

HDU - 2066

多个起点(与家临界的城市),多个终点(目的城市)

把家和目标城市分别看成一个点

注意:
1.多组数据,每次开始先把之前的数据清空
2.边会重复输入,需要保留最小的

/**
 * HDU 2066
 * vector +  dijkstra (priority_queue)
 * more start  &  more end
 * @author Hongchuan CAO
 */

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<queue>
using namespace std;

const int Maxx = 1e9;
int t,s,d;

class Node{
    public:
        int to,val;

        Node(int to,int val){
            this->to = to;
            this->val = val;
        }
};

vector<Node> path[1010];
int dis[1010];
bool use[1010];

void add_side(int a,int b,int time){
    for(int i=0;i<path[a].size();i++){
        if(path[a][i].to == b&&path[a][i].val <= time){
            return;
        }
    }

    path[a].push_back(Node(b,time));
    path[b].push_back(Node(a,time));
}

void get_data(){

    while(t--){
        int a,b,time;
        scanf("%d%d%d",&a,&b,&time);
        add_side(a,b,time);
    }

    while(s--){
        int start;
        scanf("%d",&start);
        add_side(1001,start,0);
    }

    while(d--){
        int end;
        scanf("%d",&end);
        add_side(1002,end,0);
    }
}

class cmp{
    public:
        bool operator()(Node& a, Node& b){
            return a.val>b.val;
        }
};

void dijkstra(){

    dis[1001] = 0; //the start

    priority_queue<Node,vector<Node>,cmp> pque;
    pque.push(Node(1001,0));

    while(!pque.empty()){
        Node cur = pque.top();
        pque.pop();
        int to = cur.to;
        if(use[to]) continue;
        use[to] = true;
        
        //relax
        for(auto xx : path[to]){
            if(!use[xx.to]&&dis[xx.to]>dis[to]+xx.val){
                dis[xx.to] = dis[to] + xx.val;
                pque.push(Node(xx.to,dis[xx.to]));
            }
        }
    }
    
}

void clear(){
    for(int i=0;i<1010;i++){
        path[i].clear();
        dis[i] = Maxx;
        use[i] = false;
    }
}

void solve(){
    while(scanf("%d%d%d",&t,&s,&d)!=EOF){
        clear();
        get_data();
        dijkstra();
        printf("%d\n",dis[1002]);
    }
}

int main(){
    solve();
    system("pause");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值