1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| #include <iostream> #include <vector> #include <queue> using namespace std; const int inf = INT_MAX; struct Node { Node(int _p, int _v):pos(_p), val(_v){} int pos; int val; bool operator>(const Node& ano) const { return this->val > ano.val; } };
int main() { vector<vector<int>> g = { {0, 1, inf, inf, inf}, {1, 0, 1, 1, inf}, {inf, 1, 0, inf, 3 }, {inf, 1, inf, 0, 2 }, {inf, inf, 3, 2, 0 }, }; int n = (int)g.size(); vector<int> dist(n, INT_MAX); dist[0] = 0; priority_queue<Node, vector<Node>, greater<Node>> pq; pq.push(Node(0, 0)); while (!pq.empty()) { Node cur = pq.top(); pq.pop(); int from = cur.pos; int dis = cur.val; cout << from << " " << cur.val << endl; for (int to = 0; to < n; ++to) { if (g[from][to] < inf && dist[to] > dis + g[from][to]) { dist[to] = dis + g[from][to]; pq.push(Node(to, dist[to])); } } } for (auto e : dist) cout << e << " "; cout << endl;
return 0; }
|