//method finds coloring of graph to minimize conflicts //returns number of conflicts int exhaustiveColoring(graph &g, int numColors, int t) { //vector to hold answer with least conflicts seen so far //initially ever node is color 1 vector<int> bestAnswer(g.numNodes(), 1); //vector to hold answer currently being tested //also set to all color 1 vector<int> currentAnswer = bestAnswer; //int to hold number of conflicts in bestAnswer //initialized to max number of cnflicts for given graph int conflicts = g.numEdges(); //initilize starting time double startTime = (double) (clock() / CLOCKS_PER_SEC); //while time elapsed is within given time while ( (double)(clock() / CLOCKS_PER_SEC) - startTime < t) { //change graph to have coloration of currentAnswer for (int i = 0; i < currentAnswer.size(); i++) { g.setColor(i, currentAnswer[i]); } //if current graph is asgood as or better than best graph //set best graph to current graph if (g.numConflicts() <= conflicts) { conflicts = g.numConflicts(); bestAnswer = currentAnswer; } //break if all permutations of colors have been tested //algorithm is done if (!increment(currentAnswer, numColors)) { break; } } //set coloration of graph to best rsult for (int i = 0; i < bestAnswer.size(); i++) { g.setColor(i, bestAnswer[i]); } return conflicts; }
void prim(graph &g, graph &sf) // Given a weighted graph g, sets sf equal to a minimum spanning // forest on g. Uses Prim's algorithm. { NodeWeight minWeight = 0; NodeWeight minR, minP; bool edgeFound; g.clearMark(); for(int i=0; i<g.numNodes(); i++) { if(!g.isMarked(i)) { g.mark(i); for(int j=0; j<g.numNodes()-1; j++) //start at i and grow a spanning tree untill no more can be added { edgeFound = false; minWeight = MaxEdgeWeight; for(int r=0; r<g.numNodes(); r++) { for(int p=0; p<g.numNodes(); p++) { if(g.isEdge(r,p) && g.isMarked(r) && !g.isMarked(p)) { if(g.getEdgeWeight(r,p) < minWeight) { minWeight = g.getEdgeWeight(r,p); minR= r; minP= p; edgeFound = true; } } } } //if edge was found add it to the tree if(edgeFound) { g.mark(minR,minP); g.mark(minP, minR); g.mark(minP); } } } } //add marked edges to spanning forest graph for(int i=0; i<g.numNodes(); i++) { for(int j=i+1; j<g.numNodes(); j++) { if(g.isEdge(i,j) && g.isMarked(i,j)) { sf.addEdge(i,j,g.getEdgeWeight(i,j)); sf.addEdge(j,i,g.getEdgeWeight(j,i)); cout<<"adding edge "<< i << " "<< j << endl; cout<<"num edges: "<<sf.numEdges() << endl; } } } }