summaryrefslogtreecommitdiff
path: root/lib/BHeap.cc
blob: 37f63e3d228df399a6ad9a47d73525cda696b982 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#include <stdio.h>
#include "config.h"
#include "BHeap.h"
#include "CList.h"

/**********************************\
*                                  *
*         Tas binomial             *
*                                  *
\**********************************/

/*
 *
 * Le tas binomial implémenté suit exactement les algorithmes présentés dans
 * le livre "Introduction à l'algorithmique". La structure est récursive et
 * les données de l'entête sont réparties comme suit:
 *   - Degree = -1 (pour signaler que nous somme dans l'entête)
 *   - Key contient le nombre d'éléments enregistrés
 *   - Brother est le pointeur sur le premier élément du tas
 *
 */

static int d, Depths[65536];


/*
 * Cette fonction sert à afficher le contenu du tas binomial sur le stream
 * passé en argument. L'affichage sera structuré de sorte à ressembler aux
 * diagrammes présentés dans le livre "Introduction à l'algorithmique", à
 * ceci près qu'ils sont présentés à la verticale. Exemple:
 *
 *  * Head cell.
 *  |
 *  |__ 6
 *  |_  15
 *  | |__ 18
 *  |_  5
 *  | |_  10
 *  | | |__ 29
 *  | |__ 9
 *  |_  2
 *    |_  3
 *    | |_  16
 *    | | |__ 23
 *    | |__ 17
 *    |_  11
 *    | |__ 25
 *    |__ 14
 *
 */

void BHeap::Dump(ostream & os)
{
	int i;

	if (Degree == -1) {
		os << _(" * Head cell.\n |\n");
		for (i = 0; i < 65535; i++)
			Depths[i] = 1;
		d = 1;
	} else {
		for (i = 1; i <= d; i++)
			os << (Depths[i] ? " |" : "  ");
		os << (Child ? "_  " : "__ ") << Key << endl;
	}
	if (Child) {
		Depths[d] = (Brother != NULL);
		d++;
		Child->Dump(os);
		d--;
	}
	if (Brother) {
		Brother->Dump(os);
	}
}


 /*
  * Cette fonction est utilisée dans les tests "paranoïaques" pour compter
  * le nombre véritable de cellules lors d'un parcours récursif.
  */

int BHeap::rn(void)
{
	int n = 0;

	if (Degree != -1) {
		n++;
	}
	if (Child) {
		n += Child->rn();
	}
	if (Brother) {
		n += Brother->rn();
	}
	return n;
}


 /*
  * Implémentation directe de la primitive LIEN-BINOMIAL(y, z) avec y = this.
  */

void BHeap::Link(BHeap * z)
{
	Father = z;
	Brother = z->Child;
	z->Child = this;
	z->Degree = z->Degree + 1;
}


 /*
  * Implémentation de la primitive FUSIONNER-TAS-BINOMIAUX(T1, T2) avec T1 = this.
  * L'algorithme a du être inventer car il n'est pas présenté dans le livre.
  * Par contre, il s'inspire fortement de l'algorithme "Fusion" pour le
  * tri-fusion. De plus, contrairement aux indication du livre, T2 sera rajouté
  * APRES T1, et aucun tas binaire nouveau ne sera créé. (voir rapport)
  */

void BHeap::Merge(BHeap * H)
{
	BHeap *P1, *P2, *T1, *T2;

	Key += H->Key;
	H->Key = 0;

	for (P1 = this, P2 = H->Brother; P1->Brother && P2;) {
		if (P1->Brother->Degree < P2->Degree) {	// P1 < P2, jump over P1.
			P1 = P1->Brother;
		} else {	// P1 >= P2. We will insert P2 after P1.
			T1 = P1->Brother;
			T2 = P2->Brother;
			P1->Brother = P2;
			P2->Brother = T1;
			P1 = P2;
			P2 = T2;
		}
	}
	if (!(P1->Brother))
		P1->Brother = P2;
	H->Brother = NULL;
}


 /*
  * Constructeur d'un tas binomial.
  */

BHeap::BHeap(void):Degree(-1), Father(NULL), Child(NULL), Brother(NULL), FP(new CList)
{
	type = T_BHEAP;
}


 /*
  * Constructeur interne. La structure est récursive, donc nous implémentons
  * un constructeur privé.
  */

BHeap::BHeap(Key_t IKey, Datas_t const &IDatas):PriorityList(IKey, IDatas),
Degree(0), Father(NULL), Child(NULL), Brother(NULL)
{
	type = T_BHEAP;
#ifdef DEBUG
	nc++;
#endif
}


 /*
  * Le destructeur. S'il est appelé sur l'entête, nous effacons récursivement
  * la liste des pointeurs intermédiaires, ainsi que tout le tas
  * récursivement.
  */

BHeap::~BHeap(void)
{
	if (Degree == -1)
		delete FP;

	if (Child) {
		delete Child;
	}
	if (Brother) {
		delete Brother;
	}
#ifdef DEBUG
	nd++;
#endif
}


 /*
  * Implémentation directe de l'algorithme MINIMUM-TAS-BINOMIAL(T) avec T = this.
  */

Cell BHeap::Min(void)
{
	BHeap *x = this, *y = NULL;
	int min = P_INFINITY;

	for (; x; x = x->Brother) {
		if ((x->Key < min)) {
			min = x->Key;
			y = x;
		}
	}

	return y->FP;
}


 /*
  * Insertion d'une cellule déjà créé dans le tas.
  * La routine fonctionne comme dans l'algorithme conseillé.
  */

Cell BHeap::Insert(BHeap * E)
{
	BHeap *H;

	if (Degree != -1)
		exception(2, _("Insert: not over Head."));
	if (!(H = new BHeap))
		exception(5, _("Insert: No more memory."));
	H->Brother = E;
	Union(H);
	delete H;

	return ((E->FP = ((CList *) (FP->Insert(Key, E)))));
}


 /*
  * Insertion d'un couple (Clef, Données) dans le tas.
  */

Cell BHeap::Insert(Key_t IKey, Datas_t const &IDatas)
{
	BHeap *P;

	Key++;

	if (!(P = new BHeap(IKey, IDatas)))
		exception(5, _("Insert: No more memory."));
	return (Insert(P));
}


 /*
  * Implémentation de l'algorithme TAS-BINOMIAL-EXTRAIRE-MIN(T) avec T = this.
  * La clef extraite sera renvoyée et les données satellites seront écrites dans
  * la variable Datas. L'implémentation est beaucoup plus longue que
  * l'algorithme de quatre lignes présenté dans le livre mais il s'agit de la
  * traduction entre les phrases en français présentées et le langage C.
  */

Key_t BHeap::Extract_Min(Datas_t & Datas)
{
	BHeap *x, *y = NULL, *P, *P2, *P3, *Before;
	Key_t k;
	int min = P_INFINITY;

	P = Before = this;

	if (!Brother)
		exception(4, _("Extract_Min: Priority List is empty."));

	Key--;

	// 1. Trouver la racine x de clé minimum dans la liste des racines de T...

	for (x = Brother; x; x = x->Brother) {
		if ((x->Key < min)) {
			min = x->Key;
			y = x;
			Before = P;
		}
		P = x;
	}

	//    ... et supprimer x.
	Before->Brother = y->Brother;

	// 2. T' <- CREER-TAS-BINOMIAL
	Before = new BHeap;

	// 3. inverser l'ordre de la liste chaînée des fils de x,
	//    et faire pointer tête[T'] sur la tête de la liste résultante.
	//    Comme pour fusionner, nous effectuons le travail "sur place",
	//    pour éviter les problèmes dues aux recopies. (voir rapport)
	for (P = y->Child; P;) {
		P->Father = NULL;
		P2 = Before->Brother;
		P3 = P->Brother;
		Before->Brother = P;
		P->Brother = P2;
		P = P3;
	}

	// 4. T <- UNION-TAS-BINOMIAUX(T, T')
	Before->Key = 0;
	Union(Before);

	// 5. retourner x (et l'effacer)
	k = y->Key;
	y->Brother = y->Child = NULL;
	FP->Delete(Datas, ((Cell) y->FP));
	Datas = y->Datas;
	delete y;

	return k;
}


 /*
  * Implémentation de l'algorithme UNION-TAS-BINOMIAUX(T1, T2) avec T1 = this.
  * Il y a quelques changements par rapport a l'algorithme du cormen (voir rapport)
  */

PriorityList *BHeap::Union(PriorityList * P)
{
	BHeap *x, *Before, *After;

	if ((P->GetType()) != GetType())
		return GenericUnion(P);

	Merge((BHeap *) P);
	if (!(Brother)) {
		return this;
	}
	Before = this;
	x = Brother;
	After = x->Brother;
	while (After) {
		if ((x->Degree != After->Degree)
		    || ((After->Brother)
			&& (After->Brother->Degree == x->Degree))) {
			Before = x;
			x = After;
		} else {
			if (x->Key <= After->Key) {
				x->Brother = After->Brother;
				After->Link(x);
			} else {
				Before->Brother = After;
				x->Link(After);
				x = After;
			}
		}
		After = x->Brother;
	}
	return this;
}


 /*
  * Implémentation de l'algorithme TAS-BINOMIAL-DIMINUER-CLE(T,x,k) avec T = this.
  * L'implémentation de cette routine a nécessité le rajout d'une table de pointeurs
  * pour conserver une structure correcte (voir rapport)
  */

bool BHeap::Lower_Key(Cell x, Key_t NKey)
{
	BHeap *y, *z, *tx = ((BHeap *) ((CList *) x)->Datas);

	if (NKey > tx->Key)
		return false;
	tx->Key = NKey;

	for (y = tx, z = tx->Father; z && (y->Key < z->Key); y = z, z = y->Father) {
		SWAP(y->Datas, z->Datas);
		SWAP(y->Key, z->Key);
		SWAP(y->FP, z->FP);
		SWAP(((CList *) (y->FP))->Datas, ((CList *) (z->FP))->Datas);
	}

	return true;
}


 /*
  * Implémentation directe de l'algorithme TAS-BINOMIAL-SUPPRIMER(T,x) avec T = this.
  * La valeur de la clef supprimée est renvoyée par la routine et les données satellites
  * sont écrites dans la variable Datas.
  */

Key_t BHeap::Delete(Datas_t & Datas, Cell x)
{
	Key_t K;

	K = ReadKey(x);

	Lower_Key(x, M_INFINITY);
	Extract_Min(Datas);

	return K;
}


 /*
  * Booléen qui détermine si le tas est vide ou pas.
  */

bool BHeap::IsEmpty(void)
{
	return (!(Brother));
}


 /*
  * Lit la clef d'une cellule d'un tas.
  */

Key_t BHeap::ReadKey(Cell C)
{
	return ((BHeap *) ((CList *) C)->Datas)->Key;
}


 /*
  * Lit les données d'une cellule d'un tas.
  */

Datas_t BHeap::ReadDatas(Cell C)
{
	return ((BHeap *) ((CList *) C)->Datas)->Datas;
}