Advertisement
AlbertSegarra

Camí més curt

Dec 22nd, 2014
387
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <stack>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. typedef vector<int> VI;
  9. typedef vector<VI> Graph;
  10. typedef vector<bool> VB;
  11. typedef queue<int> Queue;
  12. typedef stack<int> Stack;
  13.  
  14. void shortestPath(const Graph &G, int i, int f, Stack& P) {
  15.     VB S(G.size(), false); S[i] = true;
  16.     Queue Q; Q.push(i);
  17.     VI path(G.size());
  18.     while (Q.front() != f) {
  19.         int u = Q.front(); Q.pop();
  20.         for (int arc : G[u]) {
  21.             if (not S[arc]) {
  22.                 S[arc] = true;
  23.                 Q.push(arc);
  24.                 path[arc] = u;
  25.             }
  26.         }
  27.     }
  28.     P.push(f);
  29.     while (P.top() != i) P.push(path[P.top()]);
  30. }
  31.  
  32. void printStack(Stack &P) {
  33.     cout << P.top(); P.pop();
  34.     while (not P.empty()) {
  35.         cout << ' ' << P.top(); P.pop();
  36.     }
  37.     cout << endl;
  38. }
  39.  
  40. int main() {
  41.     int n, m;
  42.     while (cin >> n >> m) {
  43.         Graph G(n, VI());
  44.         for (int i = 0; i < m; ++i) {
  45.             int x, y; cin >> x >> y;
  46.             G[x].push_back(y);
  47.         }
  48.         for (VI &V : G) sort(V.begin(), V.end());
  49.         Stack P;
  50.         shortestPath(G, 0, n - 1, P);
  51.         printStack(P);
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement