您的位置:首页 > 其它

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

2016-08-22 19:33 393 查看
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;
}


转载自北京大学暑期课课件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: