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

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

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

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

struct CNode
{
    int k;
    int w;
};

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

priority_queue pq;
bool bUsed[30010] = {0};
vector<vector > 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;
}

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

你可能感兴趣的:(acm水题)