Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- void addEdge(vector<pair<int,int>> adj[], int u, int v, int w)
- {
- adj[u].push_back({v,w});
- adj[v].push_back({u,w});
- }
- void dijkstra(vector<pair<int,int>> adj[], int V, int source)
- {
- vector<int> dis(V,-1);
- vector<int> vis(V,0);
- priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> p;
- p.push({0,source});
- while(!p.empty())
- {
- pair<int,int> q=p.top();
- p.pop();
- int d=q.first;
- int vertex=q.second;
- if(vis[vertex]==1)
- continue;
- vis[vertex]=1;
- dis[vertex]=d;
- for(auto x:adj[vertex])
- {
- if(vis[x.first]==0)
- p.push({d+x.second,x.first});
- }
- }
- for(int i=0;i<V;i++)
- cout<<dis[i]<<" ";
- }
- void printGraph(vector<pair<int,int>> adj[], int V)
- {
- for (int v = 0; v < V; ++v)
- {
- cout << "Adjacency list of vertex "
- << v << "\n";
- for (auto x : adj[v])
- cout << x.first <<" "<<x.second<<endl;
- cout<<"\n";
- }
- }
- int main()
- {
- int V = 5;
- vector<pair<int,int>> adj[V];
- addEdge(adj,0, 1, 9);
- addEdge(adj,0, 3, 4);
- addEdge(adj,1, 3, 8);
- addEdge(adj,3, 2, 3);
- addEdge(adj,3, 4, 10);
- vector<int> vis(V,0);
- printGraph(adj,V);
- dijkstra(adj,V,4);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement