Advertisement
Guest User

Untitled

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