Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. AGM-KRUSKAL(Adj,n,w[]):
  2. para v <- 1 até n, faça MAKE-SET(v) O(V)
  3. ordene as arestas em ordem não-decrescente de peso O(E lg E)
  4. para cada aresta (u,v) nesta ordem, O(E)
  5. se FIND-SET(u) != FIND-SET(v) O(E)
  6. imprima (u,v) O(V)
  7. UNION(u,v) O(V)
  8.  
  9. MAKE-SET(x):
  10. pai[x] <- x
  11. rank[x] <- 0
  12.  
  13. UNION(x,y):
  14. LINK(FIND-SET(x), FIND-SET(y))
  15.  
  16. LINK(x,y):
  17. se rank[x] > rank[y], então pai[y] <- x
  18. senão, pai[x] <- y
  19. se rank[x] = rank[y]
  20. rank[y] <- rank[y] + 1
  21.  
  22. FIND-SET(x):
  23. se pai[x] != x
  24. pai[x] <- FIND-SET(pai[x])
  25. retorne pai[x]
  26.  
  27. ------------
  28.  
  29. #include <iostream>
  30. #include <ctime>
  31. #include <list>
  32. #include <vector>
  33. #include <algorithm>
  34.  
  35. struct Aresta {
  36. int u;
  37. int v;
  38. int peso;
  39. };
  40. #define N 9
  41. list<Aresta> Adj[N];
  42. vector<Aresta> arestas;
  43.  
  44. void inicializa_arestas()
  45. {
  46. for (int u = 0; u < N; u++)
  47. for (list<Aresta>::iterator e = Adj[u].begin(); e != Adj[u].end(); e++)
  48. if (u < e->v) arestas.push_back(*e);
  49. }
  50.  
  51. void inicializa_grafo()
  52. {
  53. enum Vertices {a,b,c,d,e,f,g,h,i};
  54. //0 1 2 3 4 5 6 7 8
  55. Adj[a].push_back((Aresta){a,b,4});
  56. Adj[a].push_back((Aresta){a,h,8});
  57. Adj[b].push_back((Aresta){b,a,4});
  58. Adj[b].push_back((Aresta){b,c,8});
  59. Adj[b].push_back((Aresta){b,h,11});
  60. Adj[c].push_back((Aresta){c,b,8});
  61. Adj[c].push_back((Aresta){c,d,7});
  62. Adj[c].push_back((Aresta){c,f,4});
  63. Adj[c].push_back((Aresta){c,i,2});
  64. Adj[d].push_back((Aresta){d,c,7});
  65. Adj[d].push_back((Aresta){d,e,9});
  66. Adj[d].push_back((Aresta){d,f,14});
  67. Adj[e].push_back((Aresta){e,d,9});
  68. Adj[e].push_back((Aresta){e,f,10});
  69. Adj[f].push_back((Aresta){f,c,4});
  70. Adj[f].push_back((Aresta){f,d,14});
  71. Adj[f].push_back((Aresta){f,e,10});
  72. Adj[f].push_back((Aresta){f,g,2});
  73. Adj[g].push_back((Aresta){g,f,2});
  74. Adj[g].push_back((Aresta){g,h,1});
  75. Adj[g].push_back((Aresta){g,i,6});
  76. Adj[h].push_back((Aresta){h,a,8});
  77. Adj[h].push_back((Aresta){h,b,11});
  78. Adj[h].push_back((Aresta){h,g,1});
  79. Adj[h].push_back((Aresta){h,i,7});
  80. Adj[i].push_back((Aresta){i,c,2});
  81. Adj[i].push_back((Aresta){i,g,6});
  82. Adj[i].push_back((Aresta){i,h,7});
  83. inicializa_arestas();
  84. }
  85.  
  86. bool comp_aresta(Aresta i, Aresta j)
  87. {
  88. return i.peso < j.peso;
  89. }
  90.  
  91. sort(arestas.begin(), arestas.end(), comp_aresta);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement