示例#1
0
    public List <HeapNode> GetNeighbours(HeapNode node)
    {
        List <HeapNode> neighbours = new List <HeapNode>();

        for (int x = -1; x <= 1; x++)
        {
            for (int y = -1; y <= 1; y++)
            {
                int checkX = node.gridIndex.x + x;
                int checkY = node.gridIndex.y + y;

                if (!(x == 0 && y == 0)
                    && // grid범위 안
                    checkX >= 0 && checkX < gridSizeX && checkY >= 0 && checkY < gridSizeY
                    && // 확인 지점 walkable 여부
                    map[checkX, node.gridIndex.y].walkable &&
                    map[node.gridIndex.x, checkY].walkable &&
                    map[checkX, checkY].walkable
                    )
                {
                    neighbours.Add(map[checkX, checkY]);
                }
            }
        }

        return(neighbours);
    }
示例#2
0
            public void Heapify()
            {
                for (int i = elements.Count - 1; i > 0; i--)
                {
                    // calculate the index of parent node
                    int parentPosition;
                    // child nodes of n -> 2n+1, 2n+2
                    if (i % 2 == 0)
                    {
                        parentPosition = (i - 2) / 2;
                    }
                    else
                    {
                        parentPosition = (i - 1) / 2;
                    }
                    parentPosition = parentPosition >= 0 ? parentPosition : 0;

                    // compare child nodes with parent. replace, if smaller
                    if (elements[i].Data < elements[parentPosition].Data)
                    {
                        HeapNode tmp = elements[parentPosition];
                        elements[parentPosition] = elements[i];
                        elements[i] = tmp;
                    }
                }
            }
示例#3
0
    private void Swap(int i, int j)
    {
        HeapNode <K, V, P> temp = heap[i];

        heap[i] = heap[j];
        heap[j] = temp;
    }
示例#4
0
        internal void Add(HeapNode node)
        {
            if (head == null)
            {
                head = node;
            }
            //Replace the position of the nodes because the node to add has a lower
            //cost.
            else if (node.ExpectedCost < head.ExpectedCost)
            {
                node.Next = head;
                head      = node;
            }
            //Add the node & realign the heap.
            else
            {
                HeapNode current = head;
                while (current.Next != null && current.Next.ExpectedCost <= node.ExpectedCost)
                {
                    current = current.Next;
                }

                node.Next    = current.Next;
                current.Next = node;
            }
        }
    private void Exchange(int i, int j)
    {
        HeapNode <T> tmp = heap[i];

        heap[i] = heap[j];
        heap[j] = tmp;
    }
示例#6
0
        public void addPacket(Packet pkt)
        {
            flitCount += pkt.nrOfFlits;
            HeapNode h = new HeapNode(pkt);

            heaps[pkt.getQueue()].Enqueue(h);
        }
        public void Enqueue(D data, P priority)
        {
            if (data == null)
            {
                return;
            }

            if (this._cache.TryGetValue(data, out _))
            {
                // Adding existing node
                throw new InvalidOperationException("Node is already in queue");
            }

            if (this.Count >= this._heap.Length - 1)
            {
                this.ResizeHeap();
            }

            this.Count++;
            var node = new HeapNode(this._nodeIDCounter++)
            {
                Data = data, Priority = priority, PositionInQueue = Count
            };

            this._cache[data]      = node;
            this._heap[this.Count] = node;

            this.HeapifyUp(node);
        }
    public void Enqueue(T obj)
    {
        HeapNode <T> node = new HeapNode <T>(obj);

        heap.Add(node);
        Swim(Count);
    }
        private void ShrinkHeap()
        {
            var newArray = new HeapNode[this._heap.Length / 2];

            Array.Copy(this._heap, newArray, this.Count + 1);
            this._heap = newArray;
        }
        private void ResizeHeap()
        {
            var newArray = new HeapNode[this._heap.Length * 2];

            Array.Copy(this._heap, newArray, this.Count + 1);
            this._heap = newArray;
        }
        private void HeapifyUp(HeapNode node)
        {
            if (node.PositionInQueue < 1)
            {
                return;
            }

            int parent = node.PositionInQueue >> 1;

            if (node.PositionInQueue > 1)
            {
                parent = node.PositionInQueue >> 1;
                if (this.IsHigherPriority(this._heap[parent], node))
                {
                    return;
                }

                this.Switch(parent, node);
            }

            while (parent > 1)
            {
                parent = parent / 2;
                if (this.IsHigherPriority(this._heap[parent], node))
                {
                    break;
                }

                this.Switch(parent, node);
            }

            this._heap[node.PositionInQueue] = node;
        }
示例#12
0
            public void RemoveItem(int val)
            {
                Console.WriteLine("Remove item with value {0}", val);
                HeapNode item = new HeapNode();

                item.Data = val;
                int last = elements.Count - 1;

                // get the index of the the first occurence of item
                int index = -1;

                for (int i = 0; i < elements.Count; i++)
                {
                    if (val == elements[i].Data)
                    {
                        index = i;
                        break;
                    }
                }

                if (index == -1)
                {
                    Console.WriteLine("No element with value {0} found.", item.Data);
                    return;
                }
                else
                {
                    elements[index] = elements[last]; // replace the value at the index with value of last item in the list
                    elements.RemoveAt(last);          // remove the last element of the list, as there is a duplicate value now at the index
                    Heapify();
                }
            }
示例#13
0
        public void AddChildTest()
        {
            // Parent node
            HeapNode <float, string> node = new HeapNode <float, string>(0, "Potato");

            // Add first child
            HeapNode <float, string> child1 = new HeapNode <float, string>(2, "Tomato");

            node.AddChild(child1);

            Assert.AreEqual(child1.Parent, node);            // Child is child of node
            Assert.AreEqual(node.Children.Count, 1);         // Node has one child
            Assert.IsTrue(node.Children.Contains(child1));   // Node has child as a child
            Assert.AreEqual(node.Rank, 1);                   // Rank reflects number of children

            // Add second child
            HeapNode <float, string> child2 = new HeapNode <float, string>(7, "Orange");

            node.AddChild(child2);

            Assert.AreEqual(child2.Parent, node);            // Child is child of node
            Assert.AreEqual(node.Children.Count, 2);         // Node has one child
            Assert.IsTrue(node.Children.Contains(child1));   // Node has child1 as a child
            Assert.IsTrue(node.Children.Contains(child2));   // Node has child2 as a child
            Assert.AreEqual(node.Rank, 2);                   // Rank reflects number of children
        }
示例#14
0
 public KeyedPriorityQueue(Comparer <P> compair)
 {
     this.mPriorityHeap     = new List <HeapNode <K, V, P> >();
     this.mPriorityComparer = compair;
     this.mPlaceHolder      = new HeapNode <K, V, P>();
     this.mPriorityHeap.Add(new HeapNode <K, V, P>());
 }
示例#15
0
            private void Swap(int i, int j)
            {
                HeapNode hn = heap[i];

                heap[i] = heap[j];
                heap[j] = hn;
            }
示例#16
0
        private HeapNode Pair(HeapNode node)
        {
            HeapNode tail = null;
            HeapNode cur  = node;

            while (cur != null && cur.Next != null)
            {
                var n1 = cur;
                var n2 = cur.Next;
                cur = cur.Next.Next;

                n1.Next = tail;
                n2.Next = n1;
                tail    = n2;
            }

            while (tail != null)
            {
                var n = tail;
                tail = tail.Next.Next;
                cur  = Meld(cur, Meld(n, n.Next));
            }

            return(cur);
        }
示例#17
0
        //
        // Removes x from the children of y
        //
        private void Cut(HeapNode <T> x, HeapNode <T> y)
        {
            // remove x from the children of y
            x.left.right = x.right;
            x.right.left = x.left;

            // y lost a child, and indicate it
            y.degree--;

            // if other children than x, set y's pointer to the next child
            if (y.child == x)
            {
                y.child = x.right;
            }

            // indicate no children, if needed
            if (y.degree == 0)
            {
                y.child = null;
            }

            // add x to root list of heap
            x.left        = minNode;
            x.right       = minNode.right;
            minNode.right = x;
            x.right.left  = x;

            // indicate x has no parent
            x.parent = null;

            // indicate x is unmarked
            x.mark = false;
        }
        public void Enqueue
        (
            TKey key
            , TValue value
            , TPriority priority
        )
        {
            TValue oldHead = _size > 0 ? _heap[1].Value : null;
            int    i       = ++_size;
            int    parent  = i / 2;

            if (i == _heap.Count)
            {
                _heap.Add(_placeHolder);
            }
            var  heapNode = new HeapNode <TKey, TValue, TPriority>(key, value, priority);
            bool isHigher = IsHigher(heapNode, _heap[parent]);

            while (i > 1 && isHigher)
            {
                _heap[i] = _heap[parent];
                i        = parent;
                parent   = i / 2;
            }
            _heap[i] = heapNode;
            TValue newHead = _heap[1].Value;

            if (!newHead.Equals(oldHead))
            {
                RaiseHeadChangedEvent(oldHead, newHead);
            }
        }
        private void Swap(int i, int j)
        {
            HeapNode <K, V, P, K, V, P> node = this.heap[i];

            this.heap[i] = this.heap[j];
            this.heap[j] = node;
        }
        public void InsertTest()
        {
            // Heap
            FibonacciHeap <float, char> heap = new FibonacciHeap <float, char>();

            // Add collection of nodes
            HeapNode <float, char> node2 = heap.Insert(7, 'b');
            HeapNode <float, char> node1 = heap.Insert(3, 'a');
            HeapNode <float, char> node3 = heap.Insert(14, 'c');
            HeapNode <float, char> node4 = heap.Insert(35, 'd');

            // Check minimum is correct, and contains correct values
            Assert.AreEqual(heap.Minimum, node1);
            Assert.AreEqual(heap.Minimum.Priority, 3);
            Assert.AreEqual(heap.Minimum.Value, 'a');
            Assert.AreEqual(heap.Count, 4);

            // Insert new minimum
            HeapNode <float, char> node5 = heap.Insert(2, 'e');

            // Check minimum is correct, and contains correct values
            Assert.AreEqual(heap.Minimum, node5);
            Assert.AreEqual(heap.Minimum.Priority, 2);
            Assert.AreEqual(heap.Minimum.Value, 'e');
            Assert.AreEqual(heap.Count, 5);
        }
        public int[] TopKFrequent_MaxHeap(int[] nums, int k)
        {
            var dict = new Dictionary <int, int>();

            foreach (var num in nums)
            {
                dict[num] = dict.ContainsKey(num) ? dict[num] + 1 : 1;
            }

            var heap = new MaxHeap(nums.Length);

            foreach (var key in dict.Keys)
            {
                var node = new HeapNode(dict[key], key);
                heap.Push(node);
            }

            var res = new int[k];
            int i   = 0;

            while (!heap.IsEmpty && i < k)
            {
                var node = heap.Pop();
                res[i] = node.Value;
                i++;
            }

            return(res);
        }
        public void DecreasePriorityTest()
        {
            // Heap
            FibonacciHeap <float, char> heap = new FibonacciHeap <float, char>();

            // Add collection of nodes
            HeapNode <float, char> node2 = heap.Insert(7, 'b');
            HeapNode <float, char> node1 = heap.Insert(3, 'a');
            HeapNode <float, char> node3 = heap.Insert(14, 'c');
            HeapNode <float, char> node4 = heap.Insert(35, 'd');

            // Decrease priority of node
            heap.DecreasePriority(node4, 1);

            // Check minimum is correct, and contains correct values
            Assert.AreEqual(heap.Minimum.Priority, 1);
            Assert.AreEqual(heap.Minimum.Value, 'd');
            Assert.AreEqual(heap.Minimum, node4);
            Assert.AreEqual(heap.Count, 4);

            // Delete min so trees are consolidated
            heap.DeleteMin();

            // Decrease priority of node
            heap.DecreasePriority(node2, 0);

            // Check minimum is correct, and contains correct values
            Assert.AreEqual(heap.Minimum, node2);
            Assert.AreEqual(heap.Minimum.Priority, 0);
            Assert.AreEqual(heap.Minimum.Value, 'b');
            Assert.AreEqual(heap.Count, 3);
        }
        public void DeleteMinTest()
        {
            // Heap
            FibonacciHeap <float, char> heap = new FibonacciHeap <float, char>();

            // Add collection of nodes
            HeapNode <float, char> node2 = heap.Insert(7, 'b');
            HeapNode <float, char> node1 = heap.Insert(3, 'a');
            HeapNode <float, char> node3 = heap.Insert(14, 'c');
            HeapNode <float, char> node4 = heap.Insert(35, 'd');

            // Check minimum is correct, and contains correct values
            Assert.AreEqual(heap.Minimum, node1);
            Assert.AreEqual(heap.Minimum.Priority, 3);
            Assert.AreEqual(heap.Minimum.Value, 'a');
            Assert.AreEqual(heap.Count, 4);

            // Remove minimum element
            heap.DeleteMin();

            // Check minimum is correct, and contains correct values
            Assert.AreEqual(heap.Minimum, node2);
            Assert.AreEqual(heap.Minimum.Priority, 7);
            Assert.AreEqual(heap.Minimum.Value, 'b');
            Assert.AreEqual(heap.Count, 3);
        }
示例#24
0
        //
        // Make node y a child of x.
        //
        private void Link(HeapNode <T> y, HeapNode <T> x)
        {
            // remove y from root list of heap
            y.left.right = y.right;
            y.right.left = y.left;

            // make y a child of x
            y.parent = x;

            // If x has no children, set y to be the child of x as well as
            // y pointing to itself (as it is the only child of x)
            if (x.child == null)
            {
                x.child = y;
                y.right = y;
                y.left  = y;
            }
            else
            {
                // Attach y to the list of x's children
                y.left        = x.child;
                y.right       = x.child.right;
                x.child.right = y;
                y.right.left  = y;
            }

            // increase x's degree since we added another child
            x.degree++;

            // unmark y
            y.mark = false;
        }
示例#25
0
 // public event EventHandler<KeyedPriorityQueueEventArgs<V>> mFirstElementChanged;
 public KeyedPriorityQueue()
 {
     this.mPriorityHeap     = new List <HeapNode <K, V, P> >();
     this.mPriorityComparer = Comparer <P> .Default;
     this.mPlaceHolder      = new HeapNode <K, V, P>();
     this.mPriorityHeap.Add(new HeapNode <K, V, P>());
 }
示例#26
0
        private void Swap(int i, int j)
        {
            HeapNode <K, V, P> node = this.mPriorityHeap[i];

            this.mPriorityHeap[i] = this.mPriorityHeap[j];
            this.mPriorityHeap[j] = node;
        }
示例#27
0
    //public void sort(int[] arr)
    //{
    //    int n = arr.Length;

    //    // Build heap (rearrange array)
    //    for (int i = n / 2 - 1; i >= 0; i--)
    //        heapify(arr, n, i);

    //    // One by one extract an element from heap
    //    for (int i = n - 1; i >= 0; i--)
    //    {
    //        // Move current root to end
    //        int temp = arr[0];
    //        arr[0] = arr[i];
    //        arr[i] = temp;

    //        // call max heapify on the reduced heap
    //        heapify(arr, i, 0);
    //    }
    //}

    //  To heapify a subtree rooted with node i which is
    // an index in arr[]. n is size of heap
    static void heapify(HeapNode[] arr, int n, int i)
    {
        int         smallest = i;         // Initialize largest as root
                int l        = 2 * i + 1; // left = 2*i + 1
                int r        = 2 * i + 2; // right = 2*i + 2

        // If left child is larger than root
        if (l < n && arr[l].Data < arr[smallest].Data)
        {
            smallest = l;
        }

        // If right child is larger than largest so far
        if (r < n && arr[r].Data < arr[smallest].Data)
        {
            smallest = r;
        }

        // If largest is not root
        if (smallest != i)
        {
            HeapNode swap = arr[i];
            arr[i]        = arr[smallest];
            arr[smallest] = swap;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, smallest);
        }
    }
示例#28
0
    public int Pop()
    {
        HeapNode result = InnerList[0];
        int      p = 0, p1, p2, pn;

        InnerList[0] = InnerList[InnerList.Count - 1];
        InnerList.RemoveAt(InnerList.Count - 1);

        do
        {
            pn = p;
            p1 = (p << 1) + 1;
            p2 = (p << 1) + 2;

            if (InnerList.Count > p1 && InnerList[p].weight > InnerList[p1].weight)
            {
                p = p1;
            }

            if (InnerList.Count > p2 && InnerList[p].weight > InnerList[p2].weight)
            {
                p = p2;
            }

            if (p == pn)
            {
                break;
            }

            HeapNode h = InnerList[p];
            InnerList[p]  = InnerList[pn];
            InnerList[pn] = h;
        } while (true);
        return(result.index);
    }
示例#29
0
        private HeapNode UnifyChildNodes(HeapNode node)
        {
            HeapNode[] tmp = new HeapNode[node.ChildsCount / 2]; //必要な要素数が明らかなのでStackではなく配列

            for (int i = 0; i < tmp.Length; i++)
            {
                HeapNode x = node.PollFirstChild();
                HeapNode y = node.PollFirstChild();
                tmp[i] = this.MergeNodes(x, y);
            }

            HeapNode z;

            if (node.ChildsCount == 1) //子要素数が奇数の場合、まだ1つ残っている子要素をここで処理
            {
                z = node.PollFirstChild();
            }
            else
            {
                z = null;
            }

            for (int i = tmp.Length - 1; i >= 0; i--) //逆順ループで配列をStackのように振る舞わせる
            {
                z = this.MergeNodes(tmp[i], z);
            }

            return(z);
        }
示例#30
0
    public void Push(int index, float weight)
    {
        int p = InnerList.Count, p2;

        InnerList.Add(new HeapNode(index, weight));

        do
        {
            if (p == 0)
            {
                break;
            }
            p2 = (p - 1) >> 1;

            if (InnerList[p].weight < InnerList[p2].weight)
            {
                HeapNode h = InnerList[p];
                InnerList[p]  = InnerList[p2];
                InnerList[p2] = h;

                p = p2;
            }
            else
            {
                break;
            }
        } while (true);
    }
示例#31
0
        //
        // Makes the given node priority the newKey value and updates the heap
        // O(log n)
        //
        public void DecreaseKey(HeapNode<int> node, int newKey)
        {
            int index = node.degree;
            node.key = newKey;

            // Moves the value up the heap until a suitable point is determined
            while (index > 0 && heap[ParentIndex(index)].key <= heap[index].key)
            {
                Swap(index, ParentIndex(index));
                index = ParentIndex(index);
            }
        }
示例#32
0
        //
        // Creates the Max-heap array and places the smallest value possible in array position 0
        //
        public MaxHeap(int sz)
        {
            heap = new HeapNode<int>[sz + 5]; // +5 for safety
            Count = 0;

            //
            // Make index 0 a sentinel value
            //
            HeapNode<int> node = new HeapNode<int>(-1);
            node.key = Double.PositiveInfinity;
            heap[0] = node;
        }
示例#33
0
文件: Heap.cs 项目: KroneckerX/WCell
        public void Insert(ILabelled obj, float importance)
        {
            if (m_Size == m_Capacity)
            {
                Resize(2*m_Size);
            }

            var i = m_Size++;
            var node = new HeapNode(obj, importance);
            node.Object.Token = i;
            nodes[i] = node;

            UpHeap(i);
        }
示例#34
0
        //
        // Inserts an element (similar to Insertion; update the heap)
        // O(log n)
        //
        public void Insert(HeapNode<int> node, int key)
        {
            // Add the node to the last open position
            node.key = key;
            node.degree = ++Count;
            heap[Count] = node;

            // Moves the value up the heap until a suitable point is determined
            int current = Count;
            while (heap[current].key >= heap[ParentIndex(current)].key)
            {
                Swap(current, ParentIndex(current));
                current = ParentIndex(current);
            }
        }
示例#35
0
 public void addPacket(Packet pkt)
 {
     flitCount += pkt.nrOfFlits;
     HeapNode h = new HeapNode(pkt);
     heaps[pkt.getQueue()].Enqueue(h);
 }
示例#36
0
        //
        // Performs Dijkstra's shortest path algorithm on the the constructed PathGraph object
        //
        // @param path -- Returns the actual shortest path in the List parameter
        // @return the length of the shortest path via the return value
        //
        public int Dijkstra(List<int> path)
        {
            // Initialize all shortest paths to a node to be large and the shortest path to a start node to be 0
            InitializeSingleSource(int.MaxValue - 100000); // -100000 prevents issues with arithmetic overflow

            //
            // Create the min-Fibonacci Heap by pushing all vertices onto the Heap
            //
            int numV = graph.NumVertices();
            //FibonacciHeap<int> vertices = new FibonacciHeap<int>();
            MinHeap vertices = new MinHeap(numV);
            for (int i = 0; i < numV; i++) // VertexValues node : shortPathEst)
            {
                // Insert the weight, d, which is the short path to node i
                HeapNode<int> node = new HeapNode<int>(i);
                vertices.Insert(node, shortPathEst[i].d);
                shortPathEst[i].heapNode = node; // maintain a pointer to the object for DecreaseKey
            }

            //
            // Visit all vertices in the PathGraph (always visiting the shortest distance from the start node first)
            // Do so by using a Fibonacci Heap
            //
            while (!vertices.IsEmpty())
            {
                //
                // Acquire the minimum: min will contain a pair <shortest distance to node n, node n>
                //
                HeapNode<int> min = vertices.ExtractMin();    // Now, extract the node

                //
                // For each adjacent vertex, relax
                //
                int nodeIndex = min.data;
                List<int> adjNodes = graph.AdjacentNodes(nodeIndex);
                foreach (int neighbor in adjNodes)
                {
                    Relax(nodeIndex, neighbor, graph.GetWeight(nodeIndex, neighbor), vertices);
                }
            }

            //
            // Look at predecessors to acquire the actual shortest path
            //
            path.Add(goalNode); // Add the last node

            // Predecessor node
            int predNode = shortPathEst[goalNode].pi;

            // Loop while we have not yet reached the start node
            // If we hit a NIL, a path does not exist
            while (predNode != startNode && predNode != NIL)
            {
                path.Insert(0, predNode); // Insert at the beginning of the List; index 0
                predNode = shortPathEst[predNode].pi;
            }

            // Check if the goal node was even reachable
            if (predNode == NIL)
            {
                path.Clear();
                return NIL;
            }

            // Insert the first node at the beginning
            path.Insert(0, predNode);

            return shortPathEst[goalNode].d; // recall .d contains the shortest path length to the goalNode
        }
示例#37
0
文件: Heap.cs 项目: KroneckerX/WCell
 private void Resize(int newSize)
 {
     var newArray = new HeapNode[newSize];
     for (var i = 0; i < m_Size; i++)
     {
         newArray[i] = nodes[i];
     }
     nodes = newArray;
     m_Capacity = newSize;
 }
示例#38
0
            public int pi; // index of the node's predecessor

            #endregion Fields

            #region Constructors

            // Basic constructor
            public VertexValue(int d, int pi)
            {
                this.d = d; this.pi = pi; heapNode = null;
            }