Spoj EZDIJKST - Easy Dijkstra Problem Solution
Problem Link: https://www.spoj.com/problems/EZDIJKST/en/
Solution in C++:
- /// La ilaha illellahu muhammadur rasulullah
- ///******Bismillahir-Rahmanir-Rahim******///
- /// Abul Hasnat Tonmoy
- /// Department of CSE,23rd batch
- /// Islamic University,Bangladesh
- ///**********ALLAH IS ALMIGHTY************///
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e4 + 9;
- #define infinity 1 << 30 // 2^30
- struct node {
- int u;
- int cost;
- node(int _u, int _cost) {
- u = _u;
- cost = _cost;
- }
- bool operator<(const node& p) const { return cost > p.cost; }
- };
- void dijstkra(int n, vector<int> g[], vector<int> cost[], int source, int des) {
- int distance[n + 1];
- int f = 0;
- for (int i = 1; i <= n; i++) {
- distance[i] = infinity;
- }
- priority_queue<node> q;
- q.push(node(source, 0));
- distance[source] = 0;
- while (!q.empty()) {
- node top = q.top();
- q.pop();
- int u = top.u;
- for (int i = 0; i < (int)g[u].size(); i++) {
- int v = g[u][i];
- if (distance[u] + cost[u][i] < distance[v]) {
- distance[v] = distance[u] + cost[u][i];
- q.push(node(v, distance[v]));
- if (v == des) f = 1;
- }
- }
- }
- if (f == 1)
- else
- cout << "NO" << endl;
- }
- int main() {
- int t;
- cin >> t;
- while (t--) {
- vector<int> g[N], cost[N];
- int numNodes, numEdges, des;
- cin >> numNodes >> numEdges;
- for (int i = 0; i < numEdges; i++) {
- int u, v, w;
- cin >> u >> v >> w;
- g[u].push_back(v);
- cost[u].push_back(w);
- }
- int source;
- cin >> source >> des;
- dijstkra(numNodes, g, cost, source, des);
- }
- return 0;
- }
No comments