20-CS-122-001 Computer Science II Spring 2012
Hints For Homework Assignment 2

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

Minimum Cost Network


Consider this:

What is wrong with this code intended to update group numbers of all cities?

   void connect (int group[], int ncities, int city1, int city2) {
      for (int i=0 ; i <= ncities ; i++)
         if (group[i] == group[city2]) group[i] = group[city1];
   }

Answer: the value of group[city2] will change during execution of the loop due to the statement group[i] = group[city1]. Hence, the value of group[city2] should be saved before the loop is executed. For example, use the statement int grp = group[city2] before the loop and replace group[city2] in the conditional with grp.

What is wrong with the following?

   ...
   Cable **cables = new Cable*[ncables];
   fstream fin;
   fin.open(argv[1], ios::in);
   int count=0;
   while (fin >> cables[count]->city1 
              >> cables[count]->city2
              >> cables[count]->cost) count++;
   ...

Answer: cables[count] is a pointer, not an object so you are trying to put values into space that does not exist. The solution is to insert the line cables[count] = new Cable; before the line fin >> .... This will require some rearrangement of code.