samedi 8 août 2020

Slow algorithm in C++ Kruskals

I implemented Kruskals algorithm to find the MST within a list of nodes, e.g. -> What the list looks like "N1 N2 3". N1 first node, N2 connected node, 3 is the cost. When it comes to a small list the algorithm performs fine, but when it comes to a list with a lot of nodes the algorithm takes several minutes to finish writing to file. How can I make it faster?

#i = Node #1
#j = Node #2
#cost = The cost between these 2 nodes.

void kruskalMST(int ** cost, int parent[], int size, string nodes[]) {
  int mincost = 0;

  ofstream output("Answer.txt");

  for (int i = 0; i < size; i++)
    parent[i] = i;

  //fill file with the original nodes
  for (int i = 0; i < size; i++)
    output << nodes[i] << endl;

  //Clear one line 
  output << endl;

  int edge_count = 0;
  while (edge_count < size - 1) {
    int min = INT_MAX, a = -1, b = -1;
    for (int i = 1; i < size; i++) {
      for (int j = 0; j < size; j++) {
        if (find(i, parent) != find(j, parent) && cost[i][j] < min) {
          min = cost[i][j];
          a = i;
          b = j;
          // I och J ska följa varandra om det inte är samma får man random värde. (ignorera gammal lösning)
        }
      }
    }

    union1(a, b, parent);

    //write to file
    output << nodes[a] << " " << nodes[b] << " " << min << endl;
  }
}

Aucun commentaire:

Enregistrer un commentaire