Преглед изворни кода

Revert "So there is a way to do prioq general node removal in log(n)"

This reverts commit c51b556894713d8154cdbef2d4ac9ffcccdaa930.
Guillaume Koenig пре 7 година
родитељ
комит
03a466f0c6
1 измењених фајлова са 22 додато и 24 уклоњено
  1. 22 24
      main.go

+ 22 - 24
main.go

@@ -386,11 +386,6 @@ func (pq *prioq) Add(car *Car) {
386 386
 
387 387
 	// Rebalance tree to respect invariant
388 388
 	var i = len(pq.bintree) - 1
389
-	pq.percolateUp(i)
390
-}
391
-
392
-func (pq *prioq) percolateUp(k int) {
393
-	var i = k
394 389
 	var p = (i - 1) / 2
395 390
 	for p >= 0 && pq.bintree[p].greater(pq.bintree[i]) {
396 391
 		pq.bintree[p], pq.bintree[i] = pq.bintree[i], pq.bintree[p]
@@ -401,31 +396,25 @@ func (pq *prioq) percolateUp(k int) {
401 396
 	}
402 397
 }
403 398
 
404
-func (pq *prioq) RemoveAtIndex(k int) *Car {
399
+func (pq *prioq) Pop() *Car {
405 400
 	if len(pq.bintree) == 0 {
406 401
 		return nil
407 402
 	}
408 403
 
409
-	if k == len(pq.bintree)-1 {
410
-		elem := pq.bintree[k]
411
-		pq.bintree = pq.bintree[:k]
404
+	if len(pq.bintree) == 1 {
405
+		elem := pq.bintree[0]
406
+		pq.bintree = pq.bintree[:0]
412 407
 		return elem
413 408
 	}
414 409
 
415
-	pq.bintree[k].pqindex = -1
416
-	elem := pq.bintree[k]
417
-	// Put last element at hole
418
-	pq.bintree[k] = pq.bintree[len(pq.bintree)-1]
419
-	pq.bintree[k].pqindex = k
410
+	pq.bintree[0].pqindex = -1
411
+	elem := pq.bintree[0]
412
+	// Put last element at root
413
+	pq.bintree[0] = pq.bintree[len(pq.bintree)-1]
414
+	pq.bintree[0].pqindex = 0
420 415
 	// Remove last element
421 416
 	pq.bintree = pq.bintree[:len(pq.bintree)-1]
422 417
 
423
-	// Oops! might need to go up
424
-	if k != 0 && !pq.bintree[k].greater(pq.bintree[(k-1)/2]) {
425
-		pq.percolateUp(k)
426
-		return elem
427
-	}
428
-
429 418
 	//        1                  9
430 419
 	//    10     9	         10     12
431 420
 	//  11 12   13 14  ->  11 12   13 14
@@ -433,8 +422,7 @@ func (pq *prioq) RemoveAtIndex(k int) *Car {
433 422
 
434 423
 	// Rebalance tree to respect invariant
435 424
 	len := len(pq.bintree)
436
-	i := k
437
-	left, right := 0, 0
425
+	i, left, right := 0, 0, 0
438 426
 	for {
439 427
 		left = 2*i + 1
440 428
 		right = 2*i + 2
@@ -475,8 +463,18 @@ func (pq *prioq) RemoveAtIndex(k int) *Car {
475 463
 	return elem
476 464
 }
477 465
 
478
-func (pq *prioq) Pop() *Car {
479
-	return pq.RemoveAtIndex(0)
466
+func (pq *prioq) RemoveAtIndex(k int) *Car {
467
+	if k == 0 {
468
+		return pq.Pop()
469
+	}
470
+	pq.bintree[k].pqindex = -1
471
+	elem := pq.bintree[k]
472
+	reassign := pq.bintree[k+1:]
473
+	pq.bintree = pq.bintree[:k]
474
+	for _, c := range reassign {
475
+		pq.Add(c)
476
+	}
477
+	return elem
480 478
 }
481 479
 
482 480
 func (pq *prioq) empty() bool {