Advertisement
Guest User

Untitled

a guest
May 23rd, 2015
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <limits>
  4. #include <queue>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. typedef pair<int, int> parint;
  9. typedef vector< vector<parint> > graph;
  10. const int infinit = numeric_limits<int>::max();
  11.  
  12. void dijkstra(const graph& g, int u, vector<int>& d, vector<int>& p) {
  13. int n = g.size();
  14. vector<bool> visto(n, false);
  15. d[u] = 0;
  16. p[u] = 0;
  17. queue<parint> q;
  18. q.push(parint(u,0));
  19. while(not q.empty()) {
  20. int v = (q.front()).first;
  21. q.pop();
  22. if(not visto[v]) {
  23. visto[v] = true;
  24. for(int i = 0; i < (int)g[v].size(); ++i) {
  25. int w = g[v][i].first; //vertice adj
  26. int r = g[v][i].second;
  27. //if(not visto[w]) {
  28. if(d[w] > d[v] + r) {
  29. d[w] = d[v] + r;
  30. p[w] = v;
  31. q.push(parint(w,d[w]));
  32. }
  33. //}
  34. }
  35. }
  36. }
  37. }
  38.  
  39. void escribir(const vector<int>& c, int v0, int vf) {
  40. if(v0 != vf) {
  41. escribir(c,v0,c[vf]);
  42. cout << c[vf] << " ";
  43. }
  44.  
  45. }
  46.  
  47. bool comp(const parint& a, const parint& b) {
  48. return a.first < b.first;
  49. }
  50.  
  51. int main() {
  52. int n, m;
  53. while(cin >> n >> m) {
  54. graph g(n);
  55. for(int i = 0; i < m; ++i) {
  56. int u, v;
  57. cin >> u >> v;
  58. g[u].push_back(parint(v,1));
  59. }
  60. //ordenem les adjacencies abans de fer el dijkstra
  61. for(int i = 0; i < n; ++i) {
  62. sort(g[i].begin(), g[i].end(), comp);
  63. }
  64. vector<int> dist(n, infinit);
  65. vector<int> path(n, -1);
  66. dijkstra(g, 0, dist, path);
  67. //0 el vertex inicial
  68. //a path tindre el cami mes curt
  69. escribir(path, 0, n-1);
  70. cout << n-1 << endl;
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement