relation r, poly from, poly to

Relation
Discrete Mathematics and
Its Applications
Baojian Hua
[email protected]
Relation ADT

A relation is a triple (A, B, R)



A and B are two sets
R \supset A*B
Typical operations:




relation creation
search a vertex (or an edge)
traverse all vertexes
…
Example
G = (A, B, R)
A=B= {1, 2, 3,
1
2
3
4
5
6
4, 5, 6}
R = {(1, 2),
(2, 5),
(3, 5),
(3, 6),
(4, 1),
(4, 2),
(5, 4),
(6, 6)}
Representation

Two popular strategies:

array-based (adjacency matrix)




Keep an extensible two-dimensional array M internally
M[i][j] holds the relation info’ of <vi, vj>, if there exists
one
a generalization of the 0-1 matrix
linear list-based (adjacency list)



for every vertex vi, maintain a linear list list<vi>
list<vi> stores vi’s outing edges
Not the focus of this slide, we’d discuss this in later slides
Adjacency Matrix
0
0
1
2
3
#
# #
2
4
5
2
3
4
5
6
5
#
1
3
4
1
# #
#
#
Note the hash function:
hash (n) = n-1
Adjacency List
1
1->2
2
2->5
3
3->5
3->6
4
4->1
4->2
5
5->4
6
6->6
Notice the pointers!
Graph in C
“relation” ADT in C: Interface
// in file “relation.h”
#ifndef RELATION_H
#define RELATION_H
typedef struct relationStruct *relation;
relation newRelation ();
void insertElem (relation r, poly data);
void insertPair (relation r, poly from, poly to);
// more to come later
…
#endif
Relation Implementation #1:
Adjacency Matrix
// adjacency matrix-based implementation
#include “matrix.h”
#include “hash.h”
#include “relation.h”
struct relationStruct
{
matrix matrix;
int rows;
int columns;
// remember the index
hash hashTable;
};
0
0
1
2
3
1
2
3
# # #
Matrix Interface
// file “matrix.h”
#ifndef MATRIX_H
#define MATRIX_H
typedef struct matrixStruct *matrix;
matrix newMatrix ();
void matrixInsert (matrix m, int i, int j);
int matrixExtend (matrix m);
#endif
// Implementation could make use of a two// dimensional extensible array, leave to you.
Adjacency Matrix-based:
Relation Creation
relation newRelation ()
{
relation r = malloc (sizeof (*r));
r->matrix = newMatrix (); // an empty matrix
r->rows = 0;
r->columns = 0;
g->hash = newHash ();
return g;
}
Adjacency Matrix-based:
Inserting Element
void insertElem (relation r, poly data)
{
int i = matrixExtend (r->matrix);
hashInsert (r->hash, data, i);
return;
0
1
2
}
0
0
1
2
3
3
0
# # #
1
1
2
2
3
4
3
# # #
4
Relation Implementation #1:
Inserting Pairs
void insertPair (relation r, poly from, poly to)
{
int f = hashLookup (g->hash, from);
int t = hashLookup (g->hash, to);
matrixInsert (g->matrix, f, t);
0
1
2 3
4
return;
2
3
0
1
} 0
# # # #
0
1
2
3
# # #
1
2
3
4
Client Code
relation r = newRelation ();
insertElem (r, 1);
1
2
3
4
5
6
insertElem (r, 2);
…
insertElem (r, 6);
insertPair (r, 1, 2);
insertPair (r, 2, 5);
…
insertPair (r, 6, 6);