void Grafo::JsonArvoreMinima() { std::vector<Aresta *> lArestas = this->Kruskal(); int custo = 0; int id1, id2; cout << "{\"arvoreminima\":{\"arestas\":["; for(int i = 0; i < (int) lArestas.size(); i++) { Aresta * cAresta = lArestas[i]; if (i > 0) cout << ","; id1 = cAresta->GetId1(); id2 = cAresta->GetId2(); custo+= cAresta->GetPeso(); cout << "(" << id1 << "," << id2 << ")"; } cout << "],\"custo\":" << custo << "}}" << endl; }
Aresta::Aresta(const Aresta & cAresta) { this->id1 = cAresta.GetId1(); this->id2 = cAresta.GetId2(); this->peso = cAresta.GetPeso(); }
std::vector<Aresta *> Grafo::Kruskal() { std::vector<Aresta *> retorno; //so faz se nao eh direcionado if (!this->Direcionado()) { //conjunto de vertices e ranks std::vector<int> ranks; //inicializa conjunto de vertices e ranks Heap * nHeap; int tamHeapMax = 0; conjKruskal.clear(); ranks.clear(); for (int i = 0; i < tamGrafo; i++) { this->conjKruskal.push_back(i); ranks.push_back(1); for (int j =0; j < tamGrafo; j++) if (this->Conexao(i,j)) tamHeapMax++; } nHeap = new Heap(tamHeapMax); nHeap->SetTipo(MINIMO); for (int i = 0; i < tamGrafo; i++) { for (int j =i; j < tamGrafo; j++) { if (this->Conexao(i,j)) { Aresta * nAresta = new Aresta(*this->GetVertice(i).GetAresta(j)); nHeap->Push(nAresta); } } } //nHeap->ListaHeap(); int id1; int id2; int id1tmp; int id2tmp; std::vector<Aresta *> lArestas; while(nHeap->GetTamHeap() > 0 ) { Aresta * cAresta = nHeap->Pop(); id1 = cAresta->GetId1(); id2 = cAresta->GetId2(); //cout << "id1: " << id1 << " id2:" << id2 << endl; if ((id1tmp = this->BuscaKruskal(id1)) != (id2tmp = BuscaKruskal(id2))) { //cout << "conjuntos diferentes: " << "id1: " << this->BuscaKruskal(id1) << " id2: " << this->BuscaKruskal(id2) << endl; retorno.push_back(cAresta); if (ranks[id1tmp] != ranks[id2tmp]) { int maior = (ranks[id1tmp] > ranks[id2tmp] ? id1tmp : id2tmp); int menor = (ranks[id2tmp] > ranks[id1tmp] ? id1tmp : id2tmp); conjKruskal[menor] = maior; //cout << "ranks: " << " menor: " << ranks[menor] << "maior: " << ranks[maior] << endl; } else { conjKruskal[id2tmp] = id1tmp; ranks[id1tmp] += 1; //cout << "aumentou rank" << endl; } } } } return retorno; }