Minimum Heap
예제 #1
0
파일: program.cs 프로젝트: staafl/ta-hw-dsa
    // a *standard* implementation of Dijkstra's algorithm using a priority queue
    // with a minor modification for the problem
    static int GetTreeWeight(Graph graph, int hospital, int verticeCount, IEnumerable<int> hospitals)
    {
        var distances = new MinHeap<int>();

        foreach (var adj in graph[hospital])
        {
            distances.TrySetPriority(adj.Item2, adj.Item1);
        }

        // return value
        int ret = 0;

        var tree = new HashSet<int>();
        int housesAdded = 0;
        int totalHouses = verticeCount - hospitals.Count();

        while (housesAdded < totalHouses && distances.Count > 0)
        {
            // edge nearest to 'hospital'

            var min = distances.ChopHeadWithPriority();
            var weight = min.Item1;

            // the new vertex in the tree

            var v1 = min.Item2;

            // modification of algorithm:
            // sum the distance to the root of all nodes that aren't
            // hospitals

            if (!hospitals.Contains(v1))
            {
                housesAdded += 1;
                ret += weight;
            }

            tree.Add(v1);

            // update the priorities of all external neighbours of the vertex
            // we've just added

            foreach (var adj in graph[v1])
            {
                var v2 = adj.Item1;
                if (v2 == hospital)
                    continue;
                if (tree.Contains(v2))
                {
                    continue;
                }

                // perhaps improve priority
                distances.TrySetPriority(weight + adj.Item2, v2, false);

            }
        }

        return ret;
    }
예제 #2
0
        public ListNode MergeKLists1(ListNode[] lists)
        {
            ListNode result = new ListNode(0);
            ListNode pointer = result;

            MinHeap mh = new MinHeap();
            foreach (ListNode node in lists)
            {
                if (node != null)
                {
                    mh.Add(node);
                }
            }

            while (mh.Count > 0)
            {
                ListNode node = mh.PopMin();
                if (node.next != null)
                {
                    mh.Add(node.next);
                }
                pointer.next = node;
                pointer = pointer.next;
            }

            return result.next;
        }
        public void TestMinMaxHeap()
        {

            // given
            int[] a = { 1, 4, 6, 8, 10, 2, 5, 3, 0, 7 };
            int[] sortedArray = { 0, 1, 2, 3, 4, 5 , 6 , 7, 8, 10 };

            MaxHeap<int> maxh = new MaxHeap<int>();
            MinHeap<int> minh = new MinHeap<int>();

            // when
            for (int i = 0; i < a.Length; i++)
            {
                maxh.Push(a[i]);
                minh.Push(a[i]);
            }


            // then
            for (int i = 0; i < a.Length; i++)
            {
                int v = minh.Pop();
                Assert.AreEqual(v, sortedArray[i]);
            }
            
            for (int i = a.Length - 1; i >= 0 ; i--)
            {
                int v = maxh.Pop();
                Assert.AreEqual(v, sortedArray[i]);
            }


        }
예제 #4
0
        public void Contains()
        {
            MinHeap<int> heap1 = new MinHeap<int>(new int[] { 1, 2, 3, 4, 5 }),
                         heap2 = new MinHeap<int>(new int[] { 5, 4, 3, 2, 1 }),
                         heap3 = new MinHeap<int>(new int[] { 2, 4, 5, 1, 3 }),
                         heap4 = new MinHeap<int>(new int[] { 1, 2, 4, 5 }),
                         heap5 = new MinHeap<int>(new int[] { 5, 4, 2, 1 }),
                         heap6 = new MinHeap<int>(new int[] { 2, 4, 5, 1 });

            for (int i = 1; i <= 5; i++)
            {
                Assert.IsTrue(heap1.Contains(i));
                Assert.IsTrue(heap2.Contains(i));
                Assert.IsTrue(heap3.Contains(i));

                if (i != 3)
                {
                    Assert.IsTrue(heap4.Contains(i));
                    Assert.IsTrue(heap5.Contains(i));
                    Assert.IsTrue(heap6.Contains(i));
                }
                else
                {
                    Assert.IsFalse(heap4.Contains(i));
                    Assert.IsFalse(heap5.Contains(i));
                    Assert.IsFalse(heap6.Contains(i));
                }
            }
        }
예제 #5
0
        public void TestHeapBySortingStrings()
        {
            var minHeap = new MinHeap<string>(new[] { "do", "re", "mi", "fa", "sol", "la", "si", "do" });
            AssertHeapSortStrings(minHeap, minHeap.OrderBy(i => i).ToArray());

            minHeap = new MinHeap<string> { "a", "d", "b", "e", "c", "k", "o", "l", "p", "m", "q", "n", "r" };
            AssertHeapSortStrings(minHeap, minHeap.OrderBy(i => i).ToArray());
        }
예제 #6
0
        public void TestInsert()
        {
            var list = new List<int> { 1, 9, 3, 6, 5, 2, 7, 11, 9 };
            var minHeap = new MinHeap();

            list.ForEach(elem => minHeap.Add(elem));

            Assert.AreEqual(1, minHeap.peekMin());
        }
예제 #7
0
        public void ExtractMinTest()
        {
            const int N = 100;
            var minHeap = new MinHeap<int>(Enumerable.Range(0, N).Reverse());

            for (int i = 0; i < N; i++)
            {
                minHeap.ExtractMin().Should().Be(i);
            }
        }
예제 #8
0
 public void Append01()
 {
     var person1 = new Person { Age = 1 };
     var person2 = new Person { Age = 1 };
     var minheap = new MinHeap<Person, int>(2, x => x.Age);
     minheap.Append(person1);
     minheap.Append(person2);
     foreach (var x in minheap) { break; }
     Assert.AreEqual(person1, minheap.Peek());
     Assert.AreNotEqual(person2, minheap.Peek());
 }
 public static void Run()
 {
     using (FastScanner fs = new FastScanner(new BufferedStream(Console.OpenStandardInput())))
     using (StreamWriter writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput())))
     {
         int n = fs.NextInt();
         MinHeap<int, int> heap = new MinHeap<int, int>();
         List<string> list = new List<string>(2 * n);
         for (int i = 0; i < n; i++)
         {
             string line = fs.ReadLine();
             string[] tokens = line.Split();
             string cmd = tokens[0];
             if (cmd == "insert") {
                 int x = Convert.ToInt32(tokens[1]);
                 heap.Insert(x, x);
             }
             else if (cmd == "getMin") {
                 int x = Convert.ToInt32(tokens[1]);
                 if (heap.Count > 0)
                 {
                     int min = heap.GetMin().Value;
                     while (min < x)
                     {
                         heap.ExtractMin();
                         list.Add("removeMin");
                         if (heap.Count == 0) break;
                         else min = heap.GetMin().Value;
                     }
                     if (heap.Count == 0 || min > x)
                     {
                         heap.Insert(x, x);
                         list.Add("insert " + x);
                     }
                 }
                 else
                 {
                     heap.Insert(x, x);
                     list.Add("insert " + x);
                 }
             }
             else {
                 if (heap.Count > 0) heap.ExtractMin();
                 else list.Add("insert 1");
             }
             list.Add(line);
         }
         writer.WriteLine(list.Count);
         foreach (string line in list)
         {
             writer.WriteLine(line);
         }
     }
 }
예제 #10
0
        public void MinHeap_ExtractRoot_ReturnsMin()
        {
            List<int> testNumbers = GetTestNumbers();
            MinHeap<int> heap = new MinHeap<int>();
            heap.AddRange(testNumbers);
            int expected = testNumbers.Min();

            int min = heap.ExtractRoot();

            Assert.AreEqual(expected, min);
        }
예제 #11
0
 public static void TestMinHeap()
 {
     MinHeap<int> minHeap = new MinHeap<int>();
     minHeap.Insert(1);
     minHeap.Insert(2);
     minHeap.Insert(5);
     minHeap.Insert(4);
     minHeap.Insert(0);
     minHeap.RemoveMin();
     minHeap.RemoveMin();
 }
예제 #12
0
        public void RemoveItemsFromMinHeapCorrectlyUpdatesMinimum()
        {
            MinHeap<int> heap = new MinHeap<int>();

            heap.Add(5);
            heap.Add(3);
            heap.Add(7);

            Assert.AreEqual(3, heap.RemoveMin());

            Assert.AreEqual(5, heap.Minimum);
        }
예제 #13
0
        public AStar()
        {
            _edgeRepository = new EdgeRepository();
            _stationService = new StationService();

            _closedSet = new List<Station>();
            _openSet = new MinHeap<Station, List<Station>>(1064);
            _cameFrom = new Dictionary<Station, Station>();
            _gScores = new Dictionary<int, decimal>();
            _fScores = new Dictionary<Station, decimal>();
            _path = new List<Station>();
        }
예제 #14
0
        public void InsertLotsOfNumbersToMinHeap()
        {
            var numbers = new int[] {
                12,12,12,12,12,12,13,12,13,11,12,12,13,12,12,12,13,13,12,13,13,13,12,12,13,12,13,12,13,13,12,14,12,12,13,12,12,13,13,12,14,13,12,12,13,13,13,13,13,13,13,12,13,13,14,13,13,13,13,13,
            };

            MinHeap<int> heap = new MinHeap<int>(100, Comparer<int>.Default);
            foreach (var number in numbers)
                heap.Add(number);
            while (heap.Count > 0)
                heap.RemoveMin();
        }
예제 #15
0
        public void MinHeap_Sorts_NegativeIntegers_LowToHigh()
        {
            MinHeap<int> integerMinHeap = new MinHeap<int>();

            integerMinHeap.Push(-150);
            integerMinHeap.Push(-2);
            integerMinHeap.Push(-50);
            integerMinHeap.Push(-1);
            integerMinHeap.Push(0);

            Assert.IsTrue(ValidateIntMinHeapSort(integerMinHeap));
        }
예제 #16
0
        public Router_AFC(Coord myCoord)
            : base(myCoord)
        {
            m_injectSlot = null;

            m_buf = new MinHeap<AFCBufferSlot>[5, Config.afc_vnets];
            for (int pc = 0; pc < 5; pc++)
                for (int i = 0; i < Config.afc_vnets; i++)
                    m_buf[pc, i] = new MinHeap<AFCBufferSlot>();

            m_buffered = false;
            m_buf_occupancy = 0;
        }
예제 #17
0
        public void AddItemToMinHeapCorrectlyUpdatesMinimum()
        {
            MinHeap<int> heap = new MinHeap<int>();

            heap.Add(5);
            Assert.AreEqual(5, heap.Minimum);

            heap.Add(3);
            Assert.AreEqual(3, heap.Minimum);

            heap.Add(7);
            Assert.AreEqual(3, heap.Minimum);
        }
예제 #18
0
        public void TestHeapBySortingObjects()
        {
            var productOne = new TestProduct("ProductOne", 100M);
            var productTwo = new TestProduct("ProductTwo", 1000M);
            var productThree = new TestProduct("ProductOne", 20M);
            var productSame = new TestProduct("ProductOne", 20M);
            var productFour = new TestProduct("ProductOne", 200M);
            var productFive = new TestProduct("ProductOne", 500M);

            var minHeap = new MinHeap<TestProduct> { productOne, productTwo, productThree, productSame, productFour, productFive };
            var actual = minHeap.ExtractDominating();
            Assert.AreEqual(productThree, actual);
        }
예제 #19
0
        /// <summary>
        /// call this to plan a path between points
        /// </summary>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public Route FindRoute(Location begin, Location end)
        {
            HashSet<MapTile> tilesToReset = new HashSet<MapTile>();//all tiles that need to be reset

            MapTile mapEnd = Map[end.Row, end.Col];
            MapTile mapBegin = Map[begin.Row, begin.Col];
            tilesToReset.Add(mapBegin);

            mapBegin.CostKnown = 0;
            mapBegin.Heuristic = Globals.state.GetDistance(begin, end);
            mapBegin.CostEstimate = mapBegin.CostKnown + mapBegin.Heuristic;

            MinHeap<MapTile> OpenSet = new MinHeap<MapTile>();
            OpenSet.Add(mapBegin);

            while (!OpenSet.IsEmpty)
            {
                MapTile current = OpenSet.ExtractMin();

                if (current == mapEnd)
                    return BuildRoute(mapEnd, tilesToReset);//reset after the oath is build, we need those pi pointers

                foreach (Direction d in (Direction[])Enum.GetValues(typeof(Direction)))
                {
                    Location tile = Globals.state.GetDestination(current.GetLocation, d);
                    MapTile neighbour = Map[tile.Row, tile.Col];

                    bool succesful = Relax(current, neighbour, mapEnd);
                    tilesToReset.Add(neighbour);//hashset will not contain duplicates

                    if (!neighbour.InOpenSet && succesful)
                    {
                        OpenSet.Add(neighbour);
                        neighbour.InOpenSet = true;//openset is a min heap, no O(1) lookup so store this in the tile
                    }
                    else
                    {

                        if (neighbour.InOpenSet && succesful)
                        {
                            OpenSet.ChangeKey(neighbour, neighbour.CostEstimate);
                        }
                    }
                }
            }

            foreach (MapTile t in tilesToReset)//no route found, still need to reset
                t.Reset();

            return null;
        }
예제 #20
0
        public void BulkInsertToMinHeap()
        {
            var values = new[] {
                1, 2, 5, 213, 25, 3, 2, 5, 3, 2, 45, 2, 5, 2, 2, 4, 6, 32, 75, 5, 47, 7, 4, 3, 5, 34, 4
            };

            var heap = new MinHeap<int>(100, Comparer<int>.Default);
            heap.Add(values);

            //Sort values and test that the heap returns them in the same order
            Array.Sort(values);
            foreach (var value in values)
                Assert.AreEqual(value, heap.RemoveMin());
        }
예제 #21
0
        public void TestHeapBySortingInts()
        {
            var minHeap = new MinHeap<int>(new[] { 9, 8, 4, 1, 6, 2, 7, 4, 1, 2 });
            AssertHeapSortInts(minHeap, minHeap.OrderBy(i => i).ToArray());

            minHeap = new MinHeap<int> { 7, 5, 1, 6, 3, 2, 4, 1, 2, 1, 3, 4, 7 };
            AssertHeapSortInts(minHeap, minHeap.OrderBy(i => i).ToArray());

            var maxHeap = new MaxHeap<int>(new[] { 1, 5, 3, 2, 7, 56, 3, 1, 23, 5, 2, 1 });
            AssertHeapSortInts(maxHeap, maxHeap.OrderBy(d => -d).ToArray());

            maxHeap = new MaxHeap<int> { 2, 6, 1, 3, 56, 1, 4, 7, 8, 23, 4, 5, 7, 34, 1, 4 };
            AssertHeapSortInts(maxHeap, maxHeap.OrderBy(d => -d).ToArray());
        }
예제 #22
0
        /// <summary>
        /// Het Dijkstra-algoritme kan alleen gebruikt worden wanneer er geen negatieve paden aanwezig zijn.
        /// Zodra deze wel aanwezig zijn zal deze functie in een oneindige lus blijven hangen.
        /// </summary>
        /// <param name="startName">Het punt waar vanuit de korste routes berekent moeten worden.</param>
        /// <returns>Returns all the considered positions</returns>
        public List<Vector2D> DijkstraWithManhattan(Vector2D startPosition, Vector2D endPosition)
        {
            MinHeap<Path> minHeap = new MinHeap<Path>();
            Node startNode = FindClosestNode(startPosition);
            Node endNode = FindClosestNode(endPosition);

            List<Vector2D> considerdPositions = new List<Vector2D>();

            clearAll();
            startNode.Distance = 0 + GetManhattanValue(startNode.Position, endNode.Position);
            minHeap.Insert(new Path(startNode, startNode.Distance));
            int nodeSeen = 0;
            while (minHeap.Count != 0 && nodeSeen < nodeMap.Count)
            {
                Path vrec = minHeap.ExtractMin();
                Node v = vrec.Destination;

                if (v.Scratch != 0)
                    continue;
                v.Scratch = 1;
                nodeSeen++;

                foreach (Edge e in v.Adjacent)
                {
                    Node w = e.destination;
                    double cvw = e.cost;
                    if (cvw < 0)
                        throw new Exception("Graph has negative edges.");

                    float heuristic1 = GetManhattanValue(w.Position, endNode.Position);
                    float heuristic2 = GetManhattanValue(v.Position, endNode.Position);

                    if (w.Distance + heuristic1 > v.Distance + heuristic2 + cvw)
                    {
                        w.Distance = v.Distance + heuristic2 + cvw;
                        w.Previous = v;

                        considerdPositions.Add(w.Position);

                        if (w.Position == endNode.Position)
                            return considerdPositions;

                        minHeap.Insert(new Path(w, w.Distance));
                    }
                }
            }

            return considerdPositions;
        }
예제 #23
0
        static void Main(string[] args)
        {
            var numbers = new int[] { 1, 5, 2, 14, 5, 1, 0 };

            var heap = new MinHeap<int>();

            foreach (var item in numbers)
            {
                heap.Insert(item);
            }

            while (heap.Count>0)
            {
                Console.WriteLine(heap.ExtractMin());
            }
        }
예제 #24
0
        public static IEnumerable<int> GetMedians(IEnumerable<int> sequence)
        {
            var enumerator = sequence.GetEnumerator();

            var smallestNumbers = new MaxHeap<int>();
            var largestNumbers = new MinHeap<int>();

            if (enumerator.MoveNext())
            {
                var number = enumerator.Current;
                smallestNumbers.Add(number);
                yield return smallestNumbers.Max;
            }

            while (enumerator.MoveNext())
            {
                var number = enumerator.Current;
                if (smallestNumbers.Count <= largestNumbers.Count)
                {
                    if (number > largestNumbers.Min)
                    {
                        var min = largestNumbers.ExtractMin();
                        smallestNumbers.Add(min);
                        largestNumbers.Add(number);
                    }
                    else
                    {
                        smallestNumbers.Add(number);
                    }
                }
                else
                {
                    if (number < smallestNumbers.Max)
                    {
                        var max = smallestNumbers.ExtractMax();
                        largestNumbers.Add(max);
                        smallestNumbers.Add(number);
                    }
                    else
                    {
                        largestNumbers.Add(number);
                    }
                }

                yield return smallestNumbers.Max;
            }
        }
예제 #25
0
	public void MinHeap()
	{
		MinHeap<int> heap = new MinHeap<int>(Comparer<int>.Default);

		for (int i = 0; i < kHeapTestSize; ++i)
			heap.Insert(Random.Range(int.MinValue + 1, int.MaxValue));

		Assert.IsTrue(heap.Validate());

		int least = int.MinValue;
		while (heap.Count > 0)
		{
			int next = heap.ExtractMin();
			Assert.IsTrue(next >= least);
			least = next;
		}
	}
예제 #26
0
        public void ExtractMin_FromHeapWithFrom1To10Elements_Successfully()
        {
            var minHeap = new MinHeap();

            for (var i = 1; i <= 10; i++)
            {
                minHeap.Add(i);
            }

            Assert.That(minHeap.ExtractMin(), Is.EqualTo(1));
            Assert.That(minHeap.ExtractMin(), Is.EqualTo(2));
            Assert.That(minHeap.ExtractMin(), Is.EqualTo(3));
            Assert.That(minHeap.ExtractMin(), Is.EqualTo(4));
            Assert.That(minHeap.ExtractMin(), Is.EqualTo(5));
            Assert.That(minHeap.Size, Is.EqualTo(5));
            Assert.That(minHeap.Min, Is.EqualTo(6));
        }
예제 #27
0
        public static void Main(string[] args)
        {
            var heap = new MinHeap<int>();

            for (int i = 0; i < 15; i++)
            {
                if (i % 2 == 0)
                {
                    i *= -1;
                }
                heap.Insert(i);

            }
            Console.WriteLine(heap.Count);
            Console.WriteLine(heap.ExtractMin());
            Console.WriteLine();
        }
예제 #28
0
파일: 1747996.cs 프로젝트: qifanyyy/CLCDSA
    public static void Main(string[] args)
    {
        var k    = int.Parse(Console.ReadLine().TrimEnd());
        var heap = new MinHeap <Node>();

        heap.Add(new Node()
        {
            Index = 1,
            Value = 1
        });
        var visited = new int[k];

        for (var i = 0; i < k; i++)
        {
            visited[i] = int.MaxValue;
        }
        visited[1] = 1;

        while (heap.Count > 0)
        {
            var cur = heap.ExtractDominating();
            if (cur.Index == 0)
            {
                Console.WriteLine(cur.Value);
                return;
            }
            if (visited[(cur.Index * 10) % k] > cur.Value)
            {
                visited[(cur.Index * 10) % k] = cur.Value;
                heap.Add(new Node()
                {
                    Index = (cur.Index * 10) % k,
                    Value = cur.Value
                });
            }
            if (visited[(cur.Index + 1) % k] > cur.Value + 1)
            {
                visited[(cur.Index + 1) % k] = cur.Value + 1;
                heap.Add(new Node()
                {
                    Index = (cur.Index + 1) % k,
                    Value = cur.Value + 1
                });
            }
        }
    }
예제 #29
0
    public List <Cell> Process()
    {
        Cell startCell = grid[(int)startPos.x, (int)startPos.y];
        Cell endCell   = grid[(int)endPos.x, (int)endPos.y];

        MinHeap        openSet   = new MinHeap(width * height);
        HashSet <Cell> closedSet = new HashSet <Cell>();

        openSet.Add(startCell);
        while (!openSet.IsEmpty())
        {
            Cell current = openSet.Pop();
            closedSet.Add(current);

            if (current == endCell)
            {
                break;
            }

            foreach (var neighbour in GetNeighbours(current))
            {
                if (!neighbour.walkable || closedSet.Contains(neighbour))
                {
                    continue;
                }

                int newCostToNeighbour = current.gCost + GetDistance(current, neighbour);
                if (!openSet.Contains(neighbour) || newCostToNeighbour < neighbour.gCost)
                {
                    neighbour.gCost  = newCostToNeighbour;
                    neighbour.hCost  = GetDistance(neighbour, endCell);
                    neighbour.parent = current;
                    if (!openSet.Contains(neighbour))
                    {
                        openSet.Add(neighbour);
                    }
                }
            }
        }

        if (openSet.IsEmpty())
        {
            return(null);
        }
        return(RetracePath(startCell, endCell));
    }
예제 #30
0
        private SliceManager()
        {
            _sliceQueue  = new MinHeap <ISlice>(new SliceCompare());
            _threadQueue = new MinHeap <ISlice>(new SliceCompare());
            _threads     = new List <ThreadRunner>();
            for (var i = 0; i < _maxThreads; i++)
            {
                _threads.Add(new ThreadRunner());
            }
            var go = new GameObject();

            Object.DontDestroyOnLoad(go);
            go.name = "__slice__runner__";
            var runnner = go.AddComponent <SliceRunner>();

            runnner.Initialize(this);
        }
예제 #31
0
        public void Dequeue()
        {
            MinHeap <int> heap       = new MinHeap <int>();
            int           targetItem = 1;
            int           targetSize = 2;

            heap.Enqueue(10);
            heap.Enqueue(5);
            heap.Enqueue(targetItem);


            int actualItem = heap.Dequeue();
            int actualSize = heap.Count();

            Assert.AreEqual(actualItem, targetItem);
            Assert.AreEqual(actualSize, targetSize);
        }
        public void DijkstraAlgorithm(int sourceVertex)
        {
            MinHeap minHeap = new MinHeap(Vertices);

            int[] distanceTable = new int[Vertices];

            //Set all distances to max value initially
            for (int i = 0; i < distanceTable.Length; i++)
            {
                distanceTable[i] = Int32.MaxValue;
            }

            //Set source vertex's distance as 0;

            minHeap.DecreaseKey(sourceVertex, 0);
            distanceTable[sourceVertex] = 0;

            while (minHeap.HeapSize > 0)
            {
                //Extract min
                MinHeapNode minNode = minHeap.ExtractMin();
                Console.WriteLine("Min value extraxted: " + minNode.Vertex);

                //Look for the node's neighbors in adjacency list
                LinkedListofGraphNodes neighbors = AdjacencyList[minNode.Vertex];
                GraphNode p = neighbors.Head;
                while (p != null)
                {
                    if (minHeap.IsinMinHeap(p.Key) && minNode.Distance != Int32.MaxValue)
                    {
                        int new_distance = minNode.Distance + p.EdgeWeight;

                        if (distanceTable[p.Key] > new_distance)
                        {
                            minHeap.DecreaseKey(p.Key, new_distance);
                            distanceTable[p.Key] = new_distance;
                        }
                    }

                    p = p.Next;
                }
            }

            PrintDistanceTable(distanceTable);
        }
예제 #33
0
        public static Node <int> ExecuteMinHeap(Node <int>[] linkedLists)       //TODO:  O()?
        {
            var storage = new MinHeap <int>();
            var k       = linkedLists.Length;

            while (true)            // load to storage
            {
                var done = true;
                for (int i = 0; i > k; i++)
                {
                    if (linkedLists[i] != null)
                    {
                        done = false;
                        storage.Add(linkedLists[i].Value);
                        linkedLists[i] = linkedLists[i].Next;
                    }
                }
                if (done)
                {
                    break;
                }
            }

            Node <int> ret;

            if (!storage.IsEmpty())
            {
                ret = new Node <int>()
                {
                    Value = storage.Poll()
                };
                var result = ret;
                while (!storage.IsEmpty())
                {
                    ret.Next = new Node <int> {
                        Value = storage.Poll()
                    };
                    ret = ret.Next;
                }

                return(result);
            }

            return(null);
        }
예제 #34
0
        public List <Edge> GetMST(Graph graph)
        {
            List <Edge>            mst           = new List <Edge>();
            MinHeap <Edge>         priorityQueue = new MinHeap <Edge>(graph.TotalNumOfEdges);
            Dictionary <int, bool> verticesInMst = new Dictionary <int, bool>();

            //1.Select any vertex from graph and put it in a set
            int vertexId = graph.Edges.ElementAt(0).Key;

            verticesInMst.Add(vertexId, true);

            while (verticesInMst.Count < graph.Edges.Count)
            {
                //2.Add all the edges from this vertex to the PriorityQueue
                foreach (Edge e in graph.Edges[vertexId])
                {
                    if ((verticesInMst.ContainsKey(e.StId) && !verticesInMst.ContainsKey(e.EndId)) ||
                        (!verticesInMst.ContainsKey(e.StId) && verticesInMst.ContainsKey(e.EndId)))
                    {
                        priorityQueue.Insert(e);
                    }
                }

                //3. Select the min weight edge such that one vertex is in set and another is not in the set.
                Edge minEdge = null;
                do
                {
                    minEdge = priorityQueue.ExtractMin();
                } while (minEdge != null && !IsOneVertexInMst(verticesInMst, minEdge));
                mst.Add(minEdge);

                // 4. Add this to the mst (list<edge>)
                if (!verticesInMst.ContainsKey(minEdge.StId))
                {
                    verticesInMst[minEdge.StId] = true;
                    vertexId = minEdge.StId;
                }
                else if (!verticesInMst.ContainsKey(minEdge.EndId))
                {
                    verticesInMst[minEdge.EndId] = true;
                    vertexId = minEdge.EndId;
                }
            }
            return(mst);
        }
예제 #35
0
        public void AssertHeapSortWithComplexType()
        {
            MinHeap <KeyValuePair <int, int> > heap = new MinHeap <KeyValuePair <int, int> >(Comparer <KeyValuePair <int, int> > .Create((x, y) => x.Value.CompareTo(y.Value)));

            heap.Add(new KeyValuePair <int, int>(3, 6));
            heap.Add(new KeyValuePair <int, int>(2, 5));
            heap.Add(new KeyValuePair <int, int>(1, 3));
            var actual = new List <int>();

            while (heap.Count > 0)
            {
                actual.Add(heap.ExtractDominating().Key);
            }
            Assert.AreEqual(actual, new List <int>()
            {
                1, 2, 3
            });
        }
예제 #36
0
        public void BuildMinHeap()
        {
            List<int> items = new List<int>()
            {
                11,28,314,3,156,561,401,359,271
            };
            var minHeap = new MinHeap<int>(items);
            Assert.AreEqual(3, minHeap.GetTop());
            var itemRemoved = minHeap.ExtractDominating();
            Assert.AreEqual(3, itemRemoved);
            Assert.AreEqual(11, minHeap.GetTop());

            var maxHeap = new MaxHeap<int>(items);
            Assert.AreEqual(561, maxHeap.GetTop());
            itemRemoved = maxHeap.ExtractDominating();
            Assert.AreEqual(561, itemRemoved);
            Assert.AreEqual(401, maxHeap.GetTop());
        }
예제 #37
0
        public void AddTest()
        {
            var heap = new MinHeap <int, int, Dictionary <int, int> >();

            var sw = new Stopwatch();

            sw.Start();

            for (int i = 0; i < 10000000; i++)
            {
                heap.Add(i, i);
            }

            sw.Stop();

            Console.WriteLine("Add elements took {0} ms.",
                              sw.ElapsedMilliseconds);
        }
예제 #38
0
        private double RebalanceAndCalculateMedian(MinHeap <double> minHeap, MaxHeap <double> maxHeap)
        {
            if (minHeap.Count == maxHeap.Count - 2)
            {
                minHeap.Add(maxHeap.Pop());
            }
            else if (maxHeap.Count == minHeap.Count - 2)
            {
                maxHeap.Add(minHeap.Pop());
            }

            if (minHeap.Count == maxHeap.Count)
            {
                return((maxHeap.Peek() + minHeap.Peek()) / 2);
            }

            return(maxHeap.Count > minHeap.Count ? maxHeap.Peek() : minHeap.Peek());
        }
예제 #39
0
        public void ShouldDeleteInsertedElement()
        {
            //Arrange
            int     value        = 1;
            int     capacity     = 2;
            MinHeap minHeap      = new MinHeap(capacity);
            var     expectedSize = 0;

            //Act
            minHeap.Insert(value);
            var deleteElement = minHeap.Pop();
            var actualSize    = minHeap.Size;

            //Assert
            Assert.True(IsHeap(minHeap.Elements, minHeap.Size));
            Assert.AreEqual(actualSize, expectedSize);
            Assert.AreEqual(value, deleteElement);
        }
예제 #40
0
    private List <Waypoint> BestFirstSearch()
    {
        MinHeap waypoints = new MinHeap();

        Evaluate(startWaypoint);
        waypoints.Insert(startWaypoint);

        while (waypoints.list.Count > 0)
        {
            Waypoint waypoint = waypoints.PullMin();
            if (waypoint == finishWaypoint)
            {
                return(MakePath(waypoint));
            }
            ExploreNeighbours(waypoints, waypoint);
        }
        return(null);
    }
예제 #41
0
        public PrimMST(WeightedGraph graph)
        {
            List <Edge> edges = new List <Edge>();

            this.graph = graph;
            queue      = new MinHeap <Edge>(graph.V());
            visited    = new bool[graph.V()];
            visit(0);

            while (!queue.isEmpty())
            {
                Edge min = queue.Popup();
                edges.Add(min);
                wt += min.Weight();
                visit(min.To());
            }
            this.edges = edges.ToArray <Edge>();
        }
예제 #42
0
        //========================================================================================================//
        //Dijkstra support methods

        //Relaxation is performed on a node once it has been popped from the heap (its min distance is now known)
        //  This function iterates through the node in questions edge list, checking if the nodes current distFromStart
        //  plus the edge weight is less than the current distance from start assigned to the destination node.
        //  If it is less, then we update the heap with the new distance.
        private static void Relaxation(MinHeap heap, HeapNode node)
        {
            //Loop through each edge in the nodes list
            foreach (var edge in node.NodeElement.EdgeList)
            {
                int destinationNodeIndex = heap.HeapElementCheck(edge.Key.Name);

                //Only analyse edges connected to nodes which remain in the heap, others are irrelevant
                if (destinationNodeIndex != -1)
                {
                    //Check if current distance + edge weight < the current distance attached to that node
                    if (node.DistFromStart + edge.Value < heap.NodeList[destinationNodeIndex].DistFromStart)
                    {
                        heap.UpdateNodeDistance(destinationNodeIndex, (node.DistFromStart + edge.Value));
                    }
                }
            }
        }
예제 #43
0
        public void AttemptToPeekOrRemoveFromEmptyMinHeapWillThrowException()
        {
            MinHeap <int> minHeap = new MinHeap <int>(IntComparer);
            int           item;

            try
            {
                item = minHeap.Peek();
                Assert.Fail("Exception Expected");
            }
            catch (NullReferenceException) { }
            try
            {
                item = minHeap.Remove();
                Assert.Fail("Exception Expected");
            }
            catch (NullReferenceException) { }
        }
예제 #44
0
        private void VerifyHeapProperty <T>(MinHeap <T> heap)
        {
            var list     = GetField <List <T> >(heap, "values");
            var comparer = GetField <IComparer <T> >(heap, "comparer");

            for (int i = 1; i <= list.Count / 2; i++)
            {
                if (i * 2 < list.Count)
                {
                    Assert.IsTrue(comparer.Compare(list[i], list[i * 2]) <= 0);
                }

                if (i * 2 + 1 < list.Count)
                {
                    Assert.IsTrue(comparer.Compare(list[i], list[i * 2 + 1]) <= 0);
                }
            }
        }
        public void RemoveTest()
        {
            MinHeap <int> heap = new MinHeap <int>();

            heap.Add(new List <int> {
                2, 5, 10
            });

            Assert.IsTrue(heap.Remove(2));
            Assert.AreEqual(5, heap.PeekMin());

            Assert.IsTrue(heap.Remove(5));
            Assert.AreEqual(10, heap.PeekMin());

            Assert.IsFalse(heap.Remove(20));
            Assert.IsTrue(heap.Remove(10));
            Assert.AreEqual(0, heap.Count);
        }
예제 #46
0
        public bool correctHeap(MinHeap <int> heap)
        {
            for (int a = 0; a < heap.list.Count; a++)
            {
                //if the node has a left child and the child is greater than the parent
                if (heap.findLeftChild(a) < heap.list.Count && heap.list[heap.findLeftChild(a)] < heap.list[a])
                {
                    return(false);
                }

                //if the node has a right child and the child is greater than the parent
                if (heap.findRightChild(a) < heap.list.Count && heap.list[heap.findRightChild(a)] < heap.list[a])
                {
                    return(false);
                }
            }
            return(true);
        }
예제 #47
0
        public void InsertTests()
        {
            int[] values  = { 2, 19, 1, 11, 10, 3, 18 };
            var   minHeap = new MinHeap <int>();

            minHeap.BuildHeap(values);
            var heap = minHeap.Heap;

            Assert.AreEqual(7, minHeap.Size);
            Assert.AreEqual(1, minHeap.GetMin());

            var expectedHeap = new int[] { 0, 1, 10, 2, 19, 11, 3, 18 };

            for (int i = 0; i < heap.Length; i++)
            {
                Assert.AreEqual(expectedHeap[i], heap[i]);
            }
        }
예제 #48
0
        public void MinHeap_Test()
        {
            var minHeap = new MinHeap <int>();

            minHeap.Insert(5);
            minHeap.Insert(3);
            minHeap.Insert(1);
            minHeap.Insert(4);
            minHeap.Insert(2);

            var result = minHeap.ExtractMin();

            Assert.AreEqual(result, 1);

            var secondResult = minHeap.ExtractMin();

            Assert.AreEqual(secondResult, 2);
        }
예제 #49
0
        public void MaintainsStructureAfterPoll()
        {
            MinHeap heap = new MinHeap(4);

            heap.Add(new Node(5));
            heap.Add(new Node(3));
            heap.Add(new Node(2));
            heap.Add(new Node(7));

            Assert.Equal(2, heap.Poll().Distance);
            Assert.Equal(3, heap.Min().Distance);

            Assert.Equal(3, heap.Poll().Distance);
            Assert.Equal(5, heap.Min().Distance);

            Assert.Equal(5, heap.Poll().Distance);
            Assert.Equal(7, heap.Min().Distance);
        }
예제 #50
0
        public void Displace01()
        {
            var minheap = new MinHeap<int>(2);
            Assert.AreEqual(0, minheap.Count());
            minheap.Insert(5);
            minheap.Insert(4);
            Assert.AreEqual(4, minheap.Displace(6));
            Assert.AreEqual(2, minheap.Count());
            Assert.AreEqual(5, minheap.Peek());

            var maxheap = new MaxHeap<int>(2);
            Assert.AreEqual(0, maxheap.Count());
            maxheap.Insert(3);
            maxheap.Insert(4);
            Assert.AreEqual(4, maxheap.Displace(2));
            Assert.AreEqual(2, maxheap.Count());
            Assert.AreEqual(3, maxheap.Peek());
        }
예제 #51
0
        public void Test2()
        {
            MinHeap <int> test = new MinHeap <int>();
            int           i;

            for (i = 0; i < 10; i++)
            {
                test.Add(i);
            }

            Assert.AreEqual(10, test.Count);

            for (i = 0; i < 10; i++)
            {
                Assert.AreEqual(i, test.ExtractMin());
                Assert.AreEqual(10 - i - 1, test.Count);
            }
        }
        public void AddCollectionAndCustomComparerCorrectOrdering()
        {
            var collection = new[]
            {
                new KeyValuePair <int, int>(3, 3),
                new KeyValuePair <int, int>(1, 1),
                new KeyValuePair <int, int>(9, 9),
                new KeyValuePair <int, int>(15, 15),
                new KeyValuePair <int, int>(2, 2)
            };

            var heap = new MinHeap <int, int, Dictionary <int, int> >(
                collection,
                Comparer <int> .Create((x, y) => - x.CompareTo(y)));

            Assert.AreEqual(5, heap.Count);
            VerifyHeapProperty(heap);
        }
예제 #53
0
    public int MinMeetingRooms(int[][] intervals)
    {
        var sorted = intervals.OrderBy(x => x[0]).ToArray();
        var ends   = new MinHeap <int>();
        var result = 0;

        foreach (var interval in sorted)
        {
            if (!ends.IsEmpty && ends.FindMin() <= interval[0])
            {
                ends.DeleteMin();
            }
            ends.Insert(interval[1]);
            result = Math.Max(result, ends.Count);
        }

        return(result);
    }
예제 #54
0
        public void Delete01()
        {
            var minheap = new MinHeap<int>(2);
            Assert.AreEqual(0, minheap.Count());
            minheap.Insert(1);
            minheap.Insert(0);
            Assert.Throws<InvalidOperationException>(() => { minheap.Insert(-1); });
            Assert.AreEqual(0, minheap.Delete());
            Assert.AreEqual(1, minheap.Count());

            var maxheap = new MaxHeap<int>(2);
            Assert.AreEqual(0, maxheap.Count());
            maxheap.Insert(0);
            maxheap.Insert(1);
            Assert.Throws<InvalidOperationException>(() => { maxheap.Insert(-1); });
            Assert.AreEqual(1, maxheap.Delete());
            Assert.AreEqual(1, maxheap.Count());
        }
예제 #55
0
        private ListNode MergeKLists(MinHeap heap)
        {
            var node = heap.Pop();

            if (node == null)
            {
                return(null);
            }
            if (heap.Length == 0)
            {
                return(node);
            }
            var head = node;

            heap.Push(node.next);
            head.next = MergeKLists(heap);
            return(head);
        }
 private static void RunDijkstra(LinkedList<int>[] adjList, int[] dist)
 {
     MinHeap<int, int> heap = new MinHeap<int, int>();
     heap.Insert(0, 0);
     dist[0] = 0;
     while (heap.Count > 0)
     {
         int u = heap.ExtractMin().Key;
         foreach (int v in adjList[u])
         {
             if (dist[v] > dist[u] + 1)
             {
                 dist[v] = dist[u] + 1;
                 heap.Insert(v, dist[v]);
             }
         }
     }
 }
예제 #57
0
        public void minHeapInsertTest()
        {
            MinHeap <int> minHeap = new MinHeap <int>();
            Random        rng     = new Random();
            int           value   = 100;

            for (int i = 0; i < value; i++)
            {
                int randnum = rng.Next(0, 100);
                minHeap.HeapifyUp(randnum);
            }
            for (int i = 1; i < value; i++)
            {
                var parent      = minHeap.Array[(i - 1) / 2];
                var currentNode = minHeap.Array[i];
                Assert.IsTrue(parent.CompareTo(currentNode) <= 0);
            }
        }
        public void TestMinHeap()
        {
            var minHeap = new MinHeap <int>(20);

            int[] a = { 1, 2, 3, 4, 5, 6, 17, 18, 19, 28, 37, 66, 55, 44, 33, 22, 11, -1, -2, -7, 3, -4, -5, -6 };
            //int[] a = { 1, 2, 3 };
            //foreach (int num in a)
            //{
            //    minHeap.Add(num);
            //}
            for (var i = 0; i < 200; i++)
            {
                minHeap.Add(i);
            }
            Assert.AreEqual(minHeap.Min, 0);
            Assert.AreEqual(minHeap.ExtractMin(), 0);
            Assert.AreEqual(minHeap.Min, 1);
        }
예제 #59
0
        static void SiftDown(ref MinHeap minHeap, int n)
        {
            var v = minHeap.heap[n];

            for (var n2 = n * 2; n2 < minHeap.count; n = n2, n2 *= 2)
            {
                if (n2 + 1 < minHeap.count && CompareCost(minHeap.heap[n2 + 1], minHeap.heap[n2]) > 0)
                {
                    n2++;
                }
                if (CompareCost(v, minHeap.heap[n2]) >= 0)
                {
                    break;
                }
                minHeap.heap[n] = minHeap.heap[n2];
            }
            minHeap.heap[n] = v;
        }
예제 #60
0
        public void PopTest()
        {
            MinHeap <int> minHeap = new MinHeap <int>(10);

            minHeap.Push(10);
            minHeap.Push(2);
            minHeap.Push(3);
            minHeap.Push(1);
            minHeap.Push(5);
            minHeap.Push(7);
            Assert.AreEqual(minHeap.Pop(), 1);
            List <int> result = new List <int>()
            {
                2, 5, 3, 10, 7
            };

            CollectionAssert.AreEqual(minHeap.display(), result);
        }