Candies(POJ 3159)(无负权边的带权有向图或无向图的单源最短路)(Dijkstra)

http://acm.hust.edu.cn/vjudge/problem/17126

思路:30000点,150000边的稀疏图求单源最短路,读入 “A B C”,就添加A->B的有向边,权值为C,然后求1到N的最短路。

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>

using namespace std;

struct CNode
{
    int k;
    int w;
};

bool operator < (const CNode &d1, const CNode &d2)
{
    return d1.w > d2.w;
}

priority_queue<CNode> pq;
bool bUsed[30010] = {0};
vector<vector<CNode> > v;
const unsigned int INF = 100000000;

int main()
{
    #ifndef ONLINE_JUDGE
    freopen ("in.txt", "r", stdin);
    #endif // ONLINE_JUDGE
    int n, m, a, b, c;
    CNode p;
    scanf ("%d%d", &n, &m);
    v.clear();
    v.resize (n + 1);
    memset (bUsed, 0, sizeof(bUsed));
    for (int i = 1; i <= m; i++) {
        scanf ("%d%d%d", &a, &b, &c);
        p.k = b;
        p.w = c;
        v[a].push_back(p);
    }
    p.k = 1;
    p.w = 0;
    pq.push(p);
    while (!pq.empty()) {
        p = pq.top();
        pq.pop();
        if (bUsed[p.k]) continue;
        bUsed[p.k] = true;
        if (p.k == n) break;
        for (int i = 0, j = v[p.k].size(); i < j; i++) {
            CNode q;
            q.k = v[p.k][i].k;
            if (bUsed[q.k]) continue;
            q.w = p.w + v[p.k][i].w;
            pq.push(q);
        }
    }
    printf ("%d", p.w);
    return 0;
}

转载自北京大学暑期课课件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值