Advertisement
jonator

shortest2

Dec 22nd, 2014
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <list>
  4. #include <queue>
  5.  
  6. using namespace std;
  7.  
  8. void escriure(list<int>& c) {
  9.   list<int>::const_iterator it;
  10.   it = c.begin();
  11.   while (it != c.end()) {
  12.     cout << *it << " ";
  13.     ++it;
  14.   }
  15.   cout << endl;
  16. }
  17.  
  18. void dijkstra(vector<vector<pair<int,int> > > &g, int u,int v){
  19.   int n = g.size();
  20.   vector<bool> vist(n,false);
  21.   vector<int> d(n,1e9);
  22.   //cami = vector<int> (n);
  23.   list<int> cami;
  24.   d[u]=0;
  25.   priority_queue<pair<int,int>, vector<pair<int,int> >, greater<pair<int,int> > > CP;
  26.   CP.push(make_pair(0,u));
  27.  
  28.   while (not CP.empty()) {
  29.     pair<int,int> q = CP.top(); CP.pop();
  30.     if (q.second == v) { escriure(cami); return; }
  31.     if (not vist[q.second]) {
  32.       vist[q.second] = true;
  33.       for (int i = 0; i < g[q.second].size(); ++i) {
  34.     int x = g[q.second][i].second;
  35.         int pes = g[q.second][i].first;
  36.     if (not vist[x]) {
  37.       if (d[x] > q.first+pes) {
  38.         d[x] = q.first+pes;
  39.         cami.push_back(q.second);
  40.         CP.push(make_pair(d[x],x));
  41.       }
  42.     }
  43.       }
  44.     }
  45.   }
  46.   cout << "no path from " << u << " to "<< v << endl;
  47. }
  48.  
  49. int main() {
  50.   int n;
  51.   while (cin >> n) {
  52.     vector<vector<pair<int,int> > > g(n);
  53.     int m;
  54.     cin >> m;
  55.     for (int i = 0; i < m; ++i) {
  56.       int u,v,pes;
  57.       cin >> u >> v >> pes;
  58.       g[u].push_back(make_pair(pes, v));
  59.     }
  60.     int x, y;
  61.     cin >> x >> y;
  62.     vector<int> c;
  63.     dijkstra(g,x,y);
  64.   }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement