예제 #1
0
UndirectedGraph* GreedyHeuristic::getICTree(UndirectedGraph* t1, UndirectedGraph* t2, list<Edge*>* iset, UndirectedGraph* ug) {

  int cardinality = ((*t1).vertices).size() - 1;
  UndirectedGraph* greedyTree = new UndirectedGraph();
  //cout << "iset size: " << iset->size() << endl;
  Edge* minE = getMinEdge(iset);
  greedyTree->addVertex(minE->fromVertex());
  greedyTree->addVertex(minE->toVertex());
  greedyTree->addEdge(minE);
  generateUCNeighborhoodFor(ug,minE);
  for (int k = 2; k < ((*ug).vertices).size(); k++) {
    Edge* newEdge = getICNeighbor(iset);
    Vertex* newVertex = NULL;
    if (greedyTree->contains(newEdge->fromVertex())) {
      newVertex = newEdge->toVertex();
    }
    else {
      newVertex = newEdge->fromVertex();
    }
    greedyTree->addVertex(newVertex);
    greedyTree->addEdge(newEdge);
    adaptUCNeighborhoodFor(newEdge,newVertex,greedyTree,ug);
  }
  if ((greedyTree->vertices).size() > (cardinality + 1)) {
    shrinkTree(greedyTree,cardinality);
  }
  greedyTree->setWeight(weightOfSolution(greedyTree));
  return greedyTree;
}
TEST(Graph, adjaent) {
  UndirectedGraph graph {20};
  graph.addEdge(0, 1);
  graph.addEdge(0, 2);
  graph.addEdge(0, 5);
  Iterator<int>* iter = graph.adjacent(0);
  EXPECT_EQ(5, iter->next());
  EXPECT_EQ(2, iter->next());
  EXPECT_EQ(1, iter->next());
}
예제 #3
0
void GreedyHeuristic::getGreedyHeuristicResult(UndirectedGraph* aTree, int cardinality, string ls_type) {

  UndirectedGraph* greedyTree = new UndirectedGraph();
  bool started = false;
  for (list<Edge*>::iterator anEdge = ((*graph).edges).begin(); anEdge != ((*graph).edges).end(); anEdge++) {
    greedyTree->clear();
    greedyTree->addVertex((*anEdge)->fromVertex());
    greedyTree->addVertex((*anEdge)->toVertex());
    greedyTree->addEdge(*anEdge);
    generateNeighborhoodFor(*anEdge);
    for (int k = 1; k < cardinality; k++) {
      Edge* kctn = getMinNeighbor();
      Vertex* nn = determineNeighborNode(kctn,greedyTree);
      greedyTree->addVertex(nn);
      greedyTree->addEdge(kctn);
      adaptNeighborhoodFor(kctn,nn,greedyTree);
    }
    if (!(ls_type == "no")) {
      
      /* application of local search */
      if (ls_type == "leafs") {
	LocalSearch lsm(graph,greedyTree);
	lsm.run(ls_type);
      }
      else {
	if (ls_type == "cycles_leafs") {
	  //cout << *greedyTree << endl;
	  LocalSearchB lsm;
	  lsm.run(graph,greedyTree);
	}
      }
      /* end local search */
      /*
      if (!isConnectedTree(greedyTree)) {
	cout << "non-connected tree" << endl;
      }
      */

    }
    greedyTree->setWeight(weightOfSolution(greedyTree));
    if (started == false) {
      started = true;
      aTree->copy(greedyTree);
    }
    else {
      if ((greedyTree->weight()) < (aTree->weight())) {
	aTree->copy(greedyTree);
      }
    }
  }
  delete(greedyTree);
}
예제 #4
0
UndirectedGraph* DirectedGraph::convertToUndirectedGraph() {
	UndirectedGraph* result = new UndirectedGraph(maxNodeId);
	for (int i = 0; i != maxNodeId + 1; i++) {
		if (!hasNode(i))
			continue;
		ListType* neighborsList = inNeighborsTable[i];
		for (ListType::iterator neighbor = neighborsList->begin();
				neighbor != neighborsList->end(); neighbor++) {
			result->addEdge(*neighbor, i);
		}
		neighborsList = outNeighborsTable[i];
		for (ListType::iterator neighbor = neighborsList->begin();
				neighbor != neighborsList->end(); neighbor++) {
			result->addEdge(*neighbor, i);
		}
	}
	result->sort();
	return result;
}
예제 #5
0
UndirectedGraph* GreedyHeuristic::uniteOnCommonBase(UndirectedGraph* t1, UndirectedGraph* t2, list<Edge*>* is) {

  UndirectedGraph* ugh = new UndirectedGraph();
  for (list<Vertex*>::iterator v = ((*t1).vertices).begin(); v != ((*t1).vertices).end(); v++) {
    ugh->addVertex(*v);
  }
  for (list<Vertex*>::iterator v = ((*t2).vertices).begin(); v != ((*t2).vertices).end(); v++) {
    if (!(ugh->contains(*v))) {
      ugh->addVertex(*v);
    }
  }
  for (list<Edge*>::iterator e = ((*t1).edges).begin(); e != ((*t1).edges).end(); e++) {
    ugh->addEdge(*e);
  }
  for (list<Edge*>::iterator e = ((*t2).edges).begin(); e != ((*t2).edges).end(); e++) {
    if (!(ugh->contains(*e))) {
      ugh->addEdge(*e);
    }
    else {
      is->push_back(*e);
    }
  }
  return ugh;
}
예제 #6
0
UndirectedGraph * readGraphFromFile(char * filename) {
    char token;
    int x=0, y=0, i=0;
    int nodes_count = 0;
    UndirectedGraph *graph;
    
    FILE *file = fopen(filename, (const char *)"r");
    if (file == NULL) {
        std::cout << "Neexistujici soubor:" << filename << endl;
        exit(EXIT_FAILURE);
    }

    if (fscanf(file, "%d", &nodes_count) != 1) {
        std:cout << "Nelze nacist prvni radek vstupniho souboru" <<endl;
        exit(EXIT_FAILURE);
    }
    
    graph = new UndirectedGraph(nodes_count);
    while (fscanf(file, "%c", &token) == 1) {
        if (token == '\r') {
            continue;
        }
        if (token == '\n') {
            //printf("\n");
            if (i > 0) {
                x=0;
                y++;
            }
            
            continue;
        }
        if(token == '1') {
            graph->addEdge(x,y);
        }
        x++;
        i++;
    }
	fclose(file);
    return graph;
}
/**
 * Removes all edges from the graph except those necessary to
 * form a minimum cost spanning tree of all vertices using Prim's
 * algorithm.
 *
 * The graph must be in a state where such a spanning tree
 * is possible. To call this method when a spanning tree is
 * impossible is undefined behavior.
 */
UndirectedGraph UndirectedGraph::minSpanningTree() {
  // Define based on the Wikipedia Pseudocode
  UndirectedGraph nug;
  
  std::priority_queue<Edge> edges;

  for (vertexmap::iterator vi = this->vertices.begin();
       vi != this->vertices.end();
       vi++)
    vi->second->setVisited(false);

  Vertex *cur = this->vertices.begin()->second;
  cur->setVisited(true);
  for (Vertex::edgemap::iterator ei = cur->edges.begin();
       ei != cur->edges.end();
       ei++)
    edges.push(ei->second);
  
  while (!edges.empty() && nug.vertices.size() < this->vertices.size()) {
    Edge small = edges.top();
    edges.pop();
    Vertex *to = small.getTo();
    
    if (to->wasVisited())
      continue;
    else {
      to->setVisited(true);
      nug.addEdge(small);
      for (Vertex::edgemap::iterator ei = to->edges.begin();
	   ei != to->edges.end();
	   ei++)
	if (!ei->second.getTo()->wasVisited())
	  edges.push(ei->second);
    }
  } // END WHILE

  return nug;
}
예제 #8
0
/**
 * Entry point into the netplan program.
 *
 * -Reads a file from the filesystem according to the specification for
 *  PA3, creating an UndirectedGraph.
 * -Finds the total cost & ping time of the graph as presented in the input
 *  file.
 * -Determines the minimum cost graph from the original graph.
 * -Finds the total cost & ping time of the minimum cost graph.
 * -Finds the change of cost & ping time from the original graph to the
 *  minimum cost graph.
 * -Prints the results to stdout.
 *
 * Usage:
 *   ./netplan infile
 *
 */
int main(int argc, char **argv) {
    // Data Structs to hold the variables
    vector<string> to;
    vector<string> from;
    vector<unsigned int> cost;
    vector<unsigned int> length;

    // if number of arguments passed in is not 2, print usage
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " infile" << std::endl;
        return EXIT_FAILURE;
    }
    
    std::ifstream in(argv[1]);
    if (!in) {
        std::cerr << "Unable to open file for reading." << std::endl;
        return EXIT_FAILURE;
    }

    // string and int variables for adding to the vectors
    string str;
    unsigned int i;

    /**
     * while file is not empty, parse input so that we can make a graph from
     * the input
     */
    while(true){
        in >> str;
        if(in.eof()) break;
        to.push_back(str);

        in >> str;
        from.push_back(str);

        in >> i;
        cost.push_back(i);

        in >> i;
        length.push_back(i);
    }

    /**
     * create undirected graph from the input file
     */
    UndirectedGraph *bob = new UndirectedGraph();
    for(unsigned int j = 0; j < to.size(); j++){
        bob->addEdge(to[j], from[j], cost[j], length[j]);
    }

    // get total edge cost of inital graph
    unsigned int totalCost = bob->totalEdgeCost();

    // get total distance of inital graph, by using Dijkstra's algorithm on 
    // all the vertices
    unsigned int totalTime = bob->totalDistance();

    // create minimum spanning tree of the inital graph, using Prim's algorithm
    bob->minSpanningTree();

    // get total edge cost of minimum spanning tree
    unsigned int mstCost = bob->totalEdgeCost();

    // get total distance of minimum spanning tree, using Dijkstra's algorithm
    // on all the vertices
    unsigned int mstTime = bob->totalDistance();

    // print out all the costs and distances
    cout << totalCost << endl;
    cout << mstCost << endl;
    cout << totalCost - mstCost << endl;
    cout << totalTime << endl;
    cout << mstTime << endl;
    cout << mstTime - totalTime << endl;

    // delete graph
    delete(bob);

    return EXIT_SUCCESS;
}
예제 #9
0
int main() {
    cout << "--------------GRAPHTESTERFILE-----------------" << endl;

    cout << "CREATING GRAPH" << endl;
    UndirectedGraph testG = UndirectedGraph();

    cout << "ADDING EDGE WITHOUT ANY VERTICES EXISTING" << endl;
    testG.addEdge("Yahoo","Google",13,13);

    cout << "total edge cost: ";
    cout << testG.totalEdgeCost() << endl;

    cout << "ADDING DUPLICATE" << endl;
    testG.addEdge("Yahoo","Google",9,9);

    cout << "total edge cost: ";
    cout << testG.totalEdgeCost() << endl;

    cout << "ADDING REVERSED DUPLICATE" << endl;
    testG.addEdge("Google","Yahoo",7,7);

    cout << "total edge cost: ";
    cout << testG.totalEdgeCost() << endl;    

    cout << "ADDING EDGE" << endl;
    testG.addEdge("Yahoo","Microsoft",71,71);
    cout << "total edge cost: ";    
    cout << testG.totalEdgeCost() << endl;

    cout << "ADDING UNCONNECTED EDGE" << endl;
    testG.addEdge("Netflix","Yelp",21,21);
    cout << "total edge cost: ";    
    cout << testG.totalEdgeCost() << endl;

    cout << "SETTING UP NON-MST" << endl;
    testG.addEdge("Google","Yahoo",2,2);
    testG.addEdge("Yahoo","Microsoft",3,3);
    testG.addEdge("Microsoft","Netflix",5,5);
    testG.addEdge("Netflix","Yelp",7,7);
    testG.addEdge("Yelp","Google",11,11);
    testG.addEdge("Netflix","Google",13,13);
    testG.addEdge("Google","Microsoft",17,17);

    cout << "total edge cost: ";    
    cout << testG.totalEdgeCost() << endl;

    cout << "CREATING MST" << endl;
    testG.minSpanningTree();
    cout << "total edge cost: ";        
    cout << testG.totalEdgeCost() << endl;

    cout << "TEST TOTAL DISTANCE" << endl;
    cout << "total distance: ";
    cout << testG.totalDistance("Google") << endl;

    cout << "TEST TOTAL DISTANCE NEW GRAPH" << endl;
    UndirectedGraph graphTwo = UndirectedGraph();
    graphTwo.addEdge("Google","Yahoo",2,2);
    graphTwo.addEdge("Yahoo","Microsoft",3,3);    
    cout << graphTwo.totalDistance("Google") << endl;
    cout << graphTwo.totalDistance("Yahoo") << endl;
    cout << graphTwo.totalDistance("Microsoft") << endl;
    cout << graphTwo.totalDistance() << endl;

    return 1;
}
TEST(Graph, add) {
  UndirectedGraph graph {20};
  graph.addEdge(0, 1);
  EXPECT_EQ(1, graph.edges());
}