Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <list>
- #include <queue>
- using namespace std;
- # define INF 0x3f3f3f3f
- typedef pair<int, int> iPair;
- class Graph
- {
- int V;
- list< pair<int, int> >* adj;
- public:
- Graph(int V);
- void addEdge(int u, int v, int w);
- void shortestPath(int s);
- };
- Graph::Graph(int V)
- {
- this->V = V;
- adj = new list<iPair>[V];
- }
- void Graph::addEdge(int u, int v, int w)
- {
- adj[u].push_back(make_pair(v, w));
- adj[v].push_back(make_pair(u, w));
- }
- void Graph::shortestPath(int src)
- {
- priority_queue< iPair, vector <iPair>, greater<iPair> > pq;
- vector<int> dist(V, INF);
- pq.push(make_pair(0, src));
- dist[src] = 0;
- while (!pq.empty())
- {
- int u = pq.top().second;
- pq.pop();
- list< pair<int, int> >::iterator i;
- for (i = adj[u].begin(); i != adj[u].end(); ++i)
- {
- int v = (*i).first;
- int weight = (*i).second;
- if (dist[v] > dist[u] + weight)
- {
- dist[v] = dist[u] + weight;
- pq.push(make_pair(dist[v], v));
- }
- }
- }
- for (int i = 1; i < V; ++i)
- cout << dist[i] << " ";
- }
- int main()
- {
- int N, M, A, B, W;
- cin >> N;
- cin >> M;
- Graph g(M);
- for (int i = 0; i < M; i++)
- {
- cin >> A >> W >> B;
- A -= 1;
- B -= 1;
- g.addEdge(A, B, W);
- }
- g.shortestPath(0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement