Advertisement
Guest User

MST Fuerza Bruta

a guest
Oct 15th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <list>
  5. #include <set>
  6. using namespace std;
  7.  
  8. #define M 1000
  9. enum V {A, B, C, D, E};
  10.  
  11. struct arista{
  12. V o;//origen
  13. V d;//destino
  14. short w;
  15. arista(V o, V d, short w) : o(o), d(d), w(w) {}
  16. };
  17.  
  18. vector<arista*> aristas;
  19. vector<bool> nodos;
  20. short nNodos = 5;
  21.  
  22. void generarGrafo(){
  23. aristas.push_back(new arista(A,B,9));
  24. aristas.push_back(new arista(A,C,8));
  25. aristas.push_back(new arista(A,E,5));
  26. aristas.push_back(new arista(B,C,6));
  27. aristas.push_back(new arista(B,D,1));
  28. aristas.push_back(new arista(B,E,4));
  29. aristas.push_back(new arista(C,D,2));
  30. aristas.push_back(new arista(D,E,3));
  31. for(short i=0; i<nNodos; i++)
  32. nodos.push_back(false);
  33. }
  34.  
  35. inline bool existe(vector<short>* A, short &id){
  36. for(short i=0; i<A->size(); i++)
  37. if(A->at(i)==id) return true;
  38. return false;
  39. }
  40. inline bool valida(short o, short d){
  41. return (!(nodos[o] && nodos[d]));
  42. }
  43.  
  44. vector<short>* MST(){
  45. vector<short>* A = new vector<short>;
  46. for(short i = 1; i<nNodos; i++){
  47. short id = 0;
  48. short id_min = 0;
  49. short min = 1000;
  50. for(arista* e : aristas){
  51. if(!existe(A, id) && valida(e->o, e->d) && min > e->w){
  52. min = e->w;
  53. id_min = id;
  54. }
  55. id++;
  56. }
  57. A->push_back(id_min);
  58. nodos[aristas[id_min]->o]=true;
  59. nodos[aristas[id_min]->d]=true;
  60. }
  61. return A;
  62. }
  63.  
  64. string nombre(short nodo){
  65. switch(nodo){
  66. case A: return "A";
  67. case B: return "B";
  68. case C: return "C";
  69. case D: return "D";
  70. case E: return "E";
  71. }
  72. return "";
  73. }
  74.  
  75. string nombrarArista(short id){
  76. return nombre(aristas[id]->o) + " - " +
  77. nombre(aristas[id]->d);
  78. }
  79.  
  80. int main() {
  81. generarGrafo();
  82. vector<short>* res = MST();
  83. cout << "El MST contiene las siguientes aristas: " << endl;
  84. for(short e_id : *res)
  85. cout << " " << nombrarArista(e_id) << endl;
  86. return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement