20-CS-122-001 Computer Science II Spring 2012
Minimum Cost Network

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      All Lectures      Source

#include <fstream>
#include <iostream>
#include <stdio.h>
using namespace std;

class Cable {
friend class CableGroup;
   int city1, city2, cost;
   bool solut;
   
 public:
   Cable (int city1, int city2, int cost) {
      solut = false;
      this->city1 = city1;
      this->city2 = city2;
      this->cost = cost;
   }

   int getCost() { return cost; }
};

int cmp (const void *x, const void *y) {
   if ((**(Cable **)x).getCost() < (**(Cable **)y).getCost()) return -1;
   if ((**(Cable **)x).getCost() > (**(Cable **)y).getCost()) return 1;
   return 0;
}

class CableGroup {
   Cable **cable;
   int *group, maxcity, ncables, index, addn;
   
 public:
   CableGroup (char *filename) {
      char buffer[1024];
      fstream fin(filename, ios::in);
      ncables = 0;
      maxcity = 0;
      while (fin.getline(buffer,1023)) {
         int city1, city2, cost;
         sscanf(buffer,"%d%d%d", &city1, &city2, &cost);
         maxcity = (maxcity < city1) ? city1 : maxcity;
         maxcity = (maxcity < city2) ? city2 : maxcity;
         ncables++;
      }
      fin.close();
      fin.clear();
      
      cable = new Cable*[ncables];
      group = new int[maxcity+1];
      for (int i=0 ; i <= maxcity ; i++) group[i] = i;
      index = addn = 0;
   }
   
   ~CableGroup () { delete cable; delete group; }
   
   Cable *nextCable () { return (index < ncables) ? cable[index++] : NULL; }
   
   void addCable (int city1, int city2, int cost) {
      cable[addn++] = new Cable(city1, city2, cost);
   }
   
   void sort () {
      qsort(cable, ncables, sizeof(Cable *), cmp);
   }
   
   bool endCitiesAlreadyConnected (Cable *cable) {
      return group[cable->city1] == group[cable->city2];
   }
   
   void addToSolution (Cable *cable) {
      cable->solut = true;
      int g1 = group[cable->city1], g2 = group[cable->city2];
      for (int k=0 ; k <= maxcity ; k++) {
         if (group[k] == g2) group[k] = g1;
      }
   }
   
   void printSolution () {
      int numb = 0, sum = 0;
      for (int i=0 ; i < ncables ; i++) {
         if (cable[i]->solut) {
            cout << "[" << cable[i]->city1 << "-" 
                        << cable[i]->city2 << ":"
                        << cable[i]->cost  << "] ";
            numb++;
            sum += cable[i]->cost;
         }
      }
      cout << "\nNumber:" << numb << " Sum:" << sum << "\n";
   }
};

int main (int argc, char **argv) {
   int city1, city2, cost;
   CableGroup cg(argv[1]);

   fstream fin(argv[1], ios::in);
   while (fin >> city1 >> city2 >> cost) cg.addCable(city1, city2, cost);
   fin.close();

   cg.sort();

   Cable *cable;
   while (cable = cg.nextCable())
      if (!cg.endCitiesAlreadyConnected(cable)) cg.addToSolution(cable);
   cg.printSolution();
}