Thursday, November 15, 2012

C++ classes: Sets

____________________________________

First: Header file.h (functions prototype).

____________________________________ 
// File: Sets.h
// Definition of Disjoint Sets Class


#ifndef SETS_H
#define SETS_H

// Specification of the class
class Sets
{
    private:
        int *p, *c, n;
    public:
        Sets(int Size): n(Size)    // Constructor
        {  
            p = new int[n+1]; c = new int[n+1];
            for (int i=0; i<=n; i++) {p[i] = -1; c[i] = 1;}
        }


        ~Sets()        // Destructor
        { delete [] p; delete [] c; }
       
        void SimpleUnion(int i, int j);
        int SimpleFind(int i);
        void dispSets() const;
};

#endif // SETS_H
#include "Sets.cpp"



________________________________________________ 

second: Implementation file.cpp 

_____________________________________

  // File: Sets.cpp
// Disjoint Sets class implementation

#include <iostream>
using namespace std;

// Make a union between set(i) and set(j)  
    void Sets::SimpleUnion(int i, int j)
    {   
        int sum = c[i] + c[j];      
        if (c[i] > c[j]) {p[j] = i; c[i] = sum;    }
        else { p[i] = j; c[j] = sum;}
    }


// Find the parent set of subset(i)
    int Sets::SimpleFind(int i)
    {     while (p[i]>=0) i = p[i];
        return i;
    }

// Display parent array
    void Sets::dispSets() const
    {
        for (int i = 1; i<=n; i++)
            cout << i <<":"<<p[i]<<":"<<c[i]<<" ";
        cout << endl;
    }
________________________________________________ 

finally class test

_____________________________________
// File: SetsTest.cpp
// Test of class Sets
#include <iostream>
using namespace std;
#include "Sets.h"


int main()  // Testing the Sets Class
{            // Union and find
    int i;
    Sets s(16);
    s.dispSets();
    s.SimpleUnion(7,1); s.SimpleUnion(8,1); s.SimpleUnion(9,1);
    s.SimpleUnion(2,5); s.SimpleUnion(10,5);
    s.SimpleUnion(4,3); s.SimpleUnion(6,3);
    s.dispSets();
    i = 1;
    cout << "parent set of " << i << " is " << s.SimpleFind(i) <<"\n";
    i = 4;
    cout << "parent set of " << i << " is " << s.SimpleFind(i) <<"\n";
    i = 10;
    cout << "parent set of " << i << " is " << s.SimpleFind(i) <<"\n";
    s.SimpleUnion(5,1);
    s.dispSets();
    i = 10;
    cout << "parent set of " << i << " is " << s.SimpleFind(i) <<"\n";


    return 0;
}


No comments:

Post a Comment