Skip to content

Instantly share code, notes, and snippets.

@rendon
Created September 23, 2021 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rendon/18fe820daac3423bb82722bd2f04ca6c to your computer and use it in GitHub Desktop.
Save rendon/18fe820daac3423bb82722bd2f04ca6c to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
int const kInf = 1 << 29;
struct edge {
int node;
int cost;
};
struct state {
int node;
int cost;
bool operator<(const state& that) const {
return cost < that.cost;
}
bool operator>(const state& that) const {
return cost > that.cost;
}
};
int findMinimumCost(vector<vector<edge>> const & graph) {
unsigned n = graph.size();
vector<int> distance(n, kInf);
vector<bool> blocked(n, false);
priority_queue<state, vector<state>, greater<state>> Q;
Q.push({0, 0});
distance[0] = 0;
while (!Q.empty()) {
int node = Q.top().node;
int cost = Q.top().cost;
Q.pop();
if (blocked[node]) {
continue;
}
blocked[node] = true;
for (auto e : graph[node]) {
int v = e.node;
if (cost + e.cost < distance[v]) {
distance[v] = cost + e.cost;
Q.push({v, cost + e.cost});
}
}
}
return distance[n-1];
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<edge>> graph(n);
for (int idx = 0; idx < m; idx++) {
int a, b, c;
cin >> a >> b >> c;
graph[a-1].push_back({b - 1, c});
graph[b-1].push_back({a - 1, c});
}
cout << findMinimumCost(graph) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment