• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Heap类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Heap的典型用法代码示例。如果您正苦于以下问题:C# Heap类的具体用法?C# Heap怎么用?C# Heap使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Heap类属于命名空间,在下文中一共展示了Heap类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: BuildMaxHeap_AllSameNumber

        public void BuildMaxHeap_AllSameNumber()
        {
            int[] array = {5, 5, 5, 5, 5, 5};
            Heap heap = new Heap(array);

            Assert.IsTrue(IsMaxHeap(heap.Queue, 0));
        }
开发者ID:jchunzh,项目名称:Algorithms,代码行数:7,代码来源:HeapTests.cs


示例2: ContainsMinHeapTest

        public void ContainsMinHeapTest()
        {
            Heap<char> actual = new Heap<char> {'g', 'r', 'a', 'n', 'v'};

            Assert.IsTrue(actual.Contains('a'));
            Assert.IsFalse(actual.Contains('l'));
        }
开发者ID:taoxiease,项目名称:asegrp,代码行数:7,代码来源:HeapTest.cs


示例3: Main

        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(@"C:\Users\Darsh\Documents\Visual Studio 2013\Projects\ProjectThree\ProjectThree\input.txt");
            Student student;
            Heap<Student> theHeap = new Heap<Student>();

            string sr = reader.ReadLine();//raid

            Student[] records = new Student[sr.Length];

            while (sr != null)// while there is still text
            {
                string[] delimiter = { ",", " " };
                string[] info = sr.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
                student = new Student(Convert.ToInt32(info[0]), Convert.ToDouble(info[1]));

                theHeap.Insert(student);//insert all data into the Heap
                sr = reader.ReadLine();
            }
            Console.WriteLine("Empty? {0}",theHeap.IsEmpty()); //false
            Console.WriteLine("Root: {0}",theHeap.GetRoot());

            theHeap.RemoveRoot();
            theHeap.Print(); //Prints out student id and gpa as min heap

            Console.WriteLine();
            Console.WriteLine("HEAPSORT!!");
            theHeap.HeapSort();//prints out the heap sort going from high to low

            Console.ReadKey();
        }
开发者ID:Kablamz,项目名称:codef,代码行数:31,代码来源:P3.cs


示例4: Dijkstra

        public static void Dijkstra(List<Tuple<int, int>>[] adj, int source, out int[] dist, out int[] pred)
        {
            int inf = int.MaxValue;
            int N = adj.Length;
            dist = new int[N];
            pred = new int[N];
            for (int i = 0; i < N; i++)
                dist[i] = inf;
            dist[source] = 0;

            Heap<int, int> heap = new Heap<int, int>(N, true);
            heap.Push(source, 0);

            while (!heap.IsEmpty())
            {
                int u = heap.PeekData();
                if (dist[u] != heap.Pop().Priority) continue;
                foreach (var tuple in adj[u])
                {
                    int v = tuple.Item1;
                    int uvWeight = tuple.Item2;
                    if (dist[v] > dist[u] + uvWeight)
                    {
                        dist[v] = dist[u] + uvWeight;
                        pred[v] = u;
                        heap.Push(v, dist[v]);
                    }
                }
            }
        }
开发者ID:psivanov,项目名称:SharpUtils,代码行数:30,代码来源:Dijkstra.cs


示例5: FindRoadPath

        /// <summary>
        /// De hoofdfunctie van de pathfinding.
        /// </summary>
        /// <param name="a">Start positie als AstarObject</param>
        /// <param name="b">Eind positie als AstarObject</param>
        /// <param name="T"> Het type weg waarin hij moet zoeken</param>
        /// <returns></returns>
        List<Point> FindRoadPath(Road a, Road b, RoadType T)
        {
            AstarObject[,] Set = new AstarObject[14, 9];
            for (int x = 0; x < 14; x++)
            {
                for (int y = 0; y < 9; y++)
                {
                    Set[x, y] = new AstarObject(x, y, this);
                }
            }

            Heap<AstarObject> OpenSet = new Heap<AstarObject>(14 * 9);
            HashSet<AstarObject> ClosedSet = new HashSet<AstarObject>();
            AstarObject Start = Set[a.X, a.Y];
            AstarObject End = Set[b.X, b.Y];
            OpenSet.Add(Start);

            while (OpenSet.Count > 0)
            {
                AstarObject CurrentLocation = OpenSet.RemoveFirst();

                ClosedSet.Add(CurrentLocation);

                if (CurrentLocation == End)
                {
                    return RetracePath(Start, End);
                    //Retracepath and stuff.
                }

                List<AstarObject> Neighbours = GetNeighbours(CurrentLocation, ref Set, NeighbourhoodType.Neumann, MapsizeXR, MapsizeYR);
                foreach (AstarObject neighbour in Neighbours)
                {
                    if (neighbour.RType != T || ClosedSet.Contains(neighbour))
                    {
                        continue;
                    }

                    int newMovementCostToNeighbour = CurrentLocation.gCost + GetDistance(CurrentLocation, neighbour);
                    if (newMovementCostToNeighbour < neighbour.gCost || !OpenSet.Contains(neighbour))
                    {
                        neighbour.gCost = newMovementCostToNeighbour;
                        neighbour.hCost = GetDistance(neighbour, End);
                        neighbour.parent = CurrentLocation;

                        if (!OpenSet.Contains(neighbour))
                        {
                            OpenSet.Add(neighbour);
                        }
                        else
                        {
                            OpenSet.UpdateItem(neighbour);
                        }

                    }

                }

            }
            return new List<Point>();
        }
开发者ID:jornvanwier,项目名称:RacegameInformaticaNHL,代码行数:67,代码来源:Game_extended.cs


示例6: Simple

        public void Simple()
        {
            var heap = new Heap<int>(HeapType.Minimum)
                           {
                               5
                           };

            Assert.AreEqual(heap.Count, 1);
            Assert.IsFalse(heap.IsEmpty);
            Assert.AreEqual(heap.Root, 5);

            heap.Add(2);
            Assert.AreEqual(heap.Count, 2);
            Assert.IsFalse(heap.IsEmpty);
            Assert.AreEqual(heap.Root, 2);

            heap.Add(3);
            Assert.AreEqual(heap.Count, 3);
            Assert.IsFalse(heap.IsEmpty);
            Assert.AreEqual(heap.Root, 2);

            Assert.AreEqual(heap.RemoveRoot(), 2);

            heap.Add(1);
            Assert.AreEqual(heap.Count, 3);
            Assert.IsFalse(heap.IsEmpty);
            Assert.AreEqual(heap.Root, 1);
        }
开发者ID:GTuritto,项目名称:ngenerics,代码行数:28,代码来源:Add.cs


示例7: Simple

        public void Simple()
        {
            var heap = new Heap<int>(HeapType.Maximum);

            Assert.AreEqual(heap.Type, HeapType.Maximum);
            Assert.AreEqual(heap.Count, 0);
            Assert.IsTrue(heap.IsEmpty);

            heap = new Heap<int>(HeapType.Maximum, Comparer<int>.Default);

            Assert.AreEqual(heap.Type, HeapType.Maximum);
            Assert.AreEqual(heap.Count, 0);
            Assert.IsTrue(heap.IsEmpty);

            heap = new Heap<int>(HeapType.Maximum, 50);

            Assert.AreEqual(heap.Type, HeapType.Maximum);
            Assert.AreEqual(heap.Count, 0);
            Assert.IsTrue(heap.IsEmpty);

            heap = new Heap<int>(HeapType.Maximum, 50, Comparer<int>.Default);

            Assert.AreEqual(heap.Type, HeapType.Maximum);
            Assert.AreEqual(heap.Count, 0);
            Assert.IsTrue(heap.IsEmpty);
        }
开发者ID:havok,项目名称:ngenerics,代码行数:26,代码来源:Construction.cs


示例8: AStar

 public AStar()
 {
     FOpenList = new Heap();
     FClosedList = new Heap();
     FSuccessors = new ArrayList();
     FSolution = new ArrayList();
 }
开发者ID:gigimoi,项目名称:ld25-Inversetroids,代码行数:7,代码来源:Safety.cs


示例9: Insert_MultipleBubbleToRoot

        public void Insert_MultipleBubbleToRoot()
        {
            Heap<int> heap = new Heap<int>(HeapType.Max)
            {
                List = new List<int>()
                {
                    150, // root
                    50,  // left child
                    100, // right child
                    45,  // left child of 50
                    40,  // right child of 50
                    95,  // left child of 100
                    90,  // right child of 100
                }
            };

            heap.Insert(200);

            Assert.AreEqual<int>(200, heap.List[0]);
            Assert.AreEqual<int>(150, heap.List[1]);
            Assert.AreEqual<int>(100, heap.List[2]);
            Assert.AreEqual<int>(50, heap.List[3]);
            Assert.AreEqual<int>(40, heap.List[4]);
            Assert.AreEqual<int>(95, heap.List[5]);
            Assert.AreEqual<int>(90, heap.List[6]);
            Assert.AreEqual<int>(45, heap.List[7]);
        }
开发者ID:furesoft,项目名称:Common,代码行数:27,代码来源:HeapTests.Integration.cs


示例10: CopyConstructorWithStrategyTest

        public void CopyConstructorWithStrategyTest()
        {
            List<string> collection = new List<string> { "Granville", "Barnett", "Luca", "Del", "Tongo" };
            Heap<string> actual = new Heap<string>(collection, Strategy.Max);

            Assert.AreEqual(5, actual.Count);
        }
开发者ID:taoxiease,项目名称:asegrp,代码行数:7,代码来源:HeapTest.cs


示例11: Main

    /* 1 Implement a class PriorityQueue<T> based
     * on the data structure "binary heap".
     * */
    static void Main(string[] args)
    {
        var heap = new Heap<int>();
        heap.Add(1);
        heap.Add(2);
        heap.Add(3);

        Debug.Assert(heap.SameContents(new[] { 1, 2, 3 }));
        Console.WriteLine(string.Join(",", heap));

        Debug.Assert(heap.ChopHead() == 3);
        Debug.Assert(heap.ChopHead() == 2);
        Debug.Assert(heap.ChopHead() == 1);
        Debug.Assert(heap.IsEmpty);

        // higher string means lower priority
        var pqueue = new PriorityQueue<string, string>((s1, s2) => -s1.CompareTo(s2));

        pqueue.Enqueue("18:00", "Buy food");
        pqueue.Enqueue("06:00", "Walk dog");
        pqueue.Enqueue("21:00", "Do homework");
        pqueue.Enqueue("09:00", "Go to work");
        pqueue.Enqueue("21:00", "Drink beer");

        Debug.Assert(pqueue.Count == 5);

        Debug.Assert(pqueue.Dequeue() == "Walk dog");
        Debug.Assert(pqueue.Dequeue() == "Go to work");
        Debug.Assert(pqueue.Dequeue() == "Buy food");
        Debug.Assert(new[] { "Do homework", "Drink beer" }.Contains(pqueue.Dequeue()));
        Debug.Assert(new[] { "Do homework", "Drink beer" }.Contains(pqueue.Dequeue()));
    }
开发者ID:staafl,项目名称:ta-hw-dsa,代码行数:35,代码来源:program.cs


示例12: TestHeapSort

        public void TestHeapSort()
        {
            Heap<int> h = new Heap<int>();
            h.Insert(500);
            h.Insert(100);
            h.Insert(200);
            h.Insert(50);
            h.Insert(1);
            h.Insert(420);
            h.Insert(3);
            h.Insert(250);
            h.Insert(5);
            h.Insert(499);

            int[] sortedItems = h.HeapSort();
            Assert.AreEqual(1, sortedItems[0]);
            Assert.AreEqual(3, sortedItems[1]);
            Assert.AreEqual(5, sortedItems[2]);
            Assert.AreEqual(50, sortedItems[3]);
            Assert.AreEqual(100, sortedItems[4]);
            Assert.AreEqual(200, sortedItems[5]);
            Assert.AreEqual(250, sortedItems[6]);
            Assert.AreEqual(420, sortedItems[7]);
            Assert.AreEqual(499, sortedItems[8]);
            Assert.AreEqual(500, sortedItems[9]);
        }
开发者ID:rajeevag,项目名称:Algorithms,代码行数:26,代码来源:HeapTests.cs


示例13: FindPath

	IEnumerator FindPath(Vector3 startPos, Vector3 targetPos) 
	{
		
		Stopwatch sw = new Stopwatch();
		sw.Start();
		
		Vector3[] waypoints = new Vector3[0];
		bool pathSuccess = false;
		
		Node startNode = grid.NodeFromWorldPoint(startPos);
		Node targetNode = grid.NodeFromWorldPoint(targetPos);
		
		if (startNode.walkable && targetNode.walkable) 
		{
			Heap<Node> openSet = new Heap<Node>(grid.MaxSize);
			HashSet<Node> closedSet = new HashSet<Node>();
			openSet.Add(startNode);
			
			while (openSet.Count > 0) 
			{
				Node currentNode = openSet.RemoveFirst();
				closedSet.Add(currentNode);
				
				if (currentNode == targetNode) 
				{
					sw.Stop();
					print ("Path found: " + sw.ElapsedMilliseconds + " ms");
					pathSuccess = true;
					break;
				}
				
				foreach (Node neighbour in grid.GetNeighbours(currentNode)) 
				{
					if (!neighbour.walkable || closedSet.Contains(neighbour)) 
					{
						continue;
					}
					
					int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour) + neighbour.movementPenalty;
					if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) 
					{
						neighbour.gCost = newMovementCostToNeighbour;
						neighbour.hCost = GetDistance(neighbour, targetNode);
						neighbour.parent = currentNode;
						
						if (!openSet.Contains(neighbour))
							openSet.Add(neighbour);
						else
							openSet.UpdateItem (neighbour);
					}
				}
			}
		}
		yield return null;
		if (pathSuccess) {
			waypoints = RetracePath(startNode,targetNode);
		}
		requestManager.FinishedProcessingPath(waypoints,pathSuccess);
		
	}
开发者ID:nathn123,项目名称:Ai-RTS-Game,代码行数:60,代码来源:Pathfinding.cs


示例14: NthSuperUglyNumber

    public int NthSuperUglyNumber(int n, int[] primes)
    {
        if(n == 1){ return 1; }
        if(primes == null || !primes.Any()){ return 1;}
        if(primes.Length == 1){ return (int)Math.Pow(primes[0],(n-1)); }

        var uglies = new int[n];
        uglies[0] = 1;
        var c = 1;

        var minHeap = new Heap(primes);

        while(c < n){
            var m = minHeap.GetMin();
            var prime = m.GetPrime(uglies);
            var index = m.UglyIndex;
            var possibility = m.Value;

            if(possibility != uglies[c-1]){
                uglies[c++] = possibility;
            }

            minHeap.ReplaceMin(uglies[index+1] * prime, index+1);
        }

        return uglies.Last();
    }
开发者ID:WillFr,项目名称:train,代码行数:27,代码来源:Solution2B.cs


示例15: FindPath

 public void FindPath(Grid _grid)
 {
     Node start = _grid.StartNode;
     Node end = _grid.EndNode;
     open = new Heap<Node>(_grid.GridMaxSize);
     close = new HashSet<Node>();
     open.Add(start);
     while (open.Count > 0)
     {
         Node current = open.GetFirst();
         if (current.GridBlock.Equals(end.GridBlock))
             return;
         foreach(Node p in _grid.GetNeighbours(current))
         {
             if (p.GridBlock.Type != GridBlock.BlockType.Obstacle || close.Contains(p))
                 continue;                                      
             int gCost = current.gCost + GetDistance(current, p);
             if(gCost < current.gCost || !open.Contains(p))
             {
                 p.gCost = gCost;
                 p.hCost = GetDistance(current, p);
                 p.Parent = current;
                 if (!open.Contains(p))
                     open.Add(p);
             }
         }
     }
 }
开发者ID:lpalma92,项目名称:pathfinding-vs,代码行数:28,代码来源:Pathfinding.cs


示例16: FindPath

	void FindPath(Vector3 startPos, Vector3 targetPos) {  // performs A* search on the grid to find a path
        startPos = new Vector3(startPos.x + 8.0f, 0, startPos.z - 2.0f); // offsets
        targetPos = new Vector3(targetPos.x + 8.0f, 0, targetPos.z - 2.0f); // offsets

        Node startNode = grid.GetNodeFromWorldPoint(startPos);
        Node targetNode = grid.GetNodeFromWorldPoint(targetPos);

        if (targetNode.walkable == false) return; // don't try to path find if we're on an unwalkable area

		Heap<Node> openSet = new Heap<Node>(grid.MaxSize); 
        HashSet<Node> closedSet = new HashSet<Node>();

        openSet.Add(startNode);
        while(openSet.Count > 0) { // we still have nodes 
			Node currentNode = openSet.pop();
            closedSet.Add(currentNode);
            if(currentNode == targetNode) { // we've found exit
                RetracePath(startNode, targetNode);
                path = backTrackPath(startNode, targetNode);
                return;
            }
            foreach(Node n in grid.GetNeighbours(currentNode)) {
                if (!n.walkable || closedSet.Contains(n)) continue;
                int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, n);
                if(newMovementCostToNeighbour < n.gCost || !openSet.contains(n)) {
                    n.gCost = newMovementCostToNeighbour;
                    n.hCost = GetDistance(n, targetNode);
                    n.parent = currentNode;

                    if (!openSet.contains(n)) openSet.Add(n); // add our neighbour into open set
					else openSet.UpdateItem(n);
                }
            }
        }
    }
开发者ID:zhang165,项目名称:Drive,代码行数:35,代码来源:PathController.cs


示例17: HeapifyDown_SwapLeft

        public void HeapifyDown_SwapLeft()
        {
            Heap<int> heap = new Heap<int>(HeapType.Max)
            {
                List = new List<int>()
                {
                    25,
                    50,
                    10
                }
            };

            using (ShimsContext.Create())
            {
                int swappedChildIx = int.MinValue;
                int swappedParentIx = int.MinValue;

                ShimHeap<int>.AllInstances.SwapInt32Int32 = (h, childIx, parentIx) =>
                {
                    swappedChildIx = childIx;
                    swappedParentIx = parentIx;
                };

                heap.HeapifyDown();

                Assert.AreEqual<int>(1, swappedChildIx);
                Assert.AreEqual<int>(0, swappedParentIx);
            }
        }
开发者ID:furesoft,项目名称:Common,代码行数:29,代码来源:HeapTests.Unit.cs


示例18: TNodeMatrixAssign

 public TNodeMatrixAssign(TNode Parent, Heap<CellMatrix> Heap, int Ref, MNode Expression)
     : base(Parent)
 {
     this._expression = Expression;
     this._ref = Ref;
     this._mat = Heap;
 }
开发者ID:pwdlugosz,项目名称:Horse,代码行数:7,代码来源:TNodeMatrixAssign.cs


示例19: ContainsMaxHeapTest

        public void ContainsMaxHeapTest()
        {
            Heap<int> actual = new Heap<int>(Strategy.Max) {23, 45, 1, 9, 12};

            Assert.IsTrue(actual.Contains(12));
            Assert.IsFalse(actual.Contains(99));
        }
开发者ID:taoxiease,项目名称:asegrp,代码行数:7,代码来源:HeapTest.cs


示例20: calc

 void calc()
 {
     Scanner cin = new Scanner();
     int n = cin.nextInt();
     int[] r = new int[n];
     int i, j;
     Dictionary<int, int> dic = new Dictionary<int, int>();
     for (i = 0; i < n; i++)
     {
         r[i] = cin.nextInt();
         if (!dic.ContainsKey(r[i])) dic[r[i]] = 0;
         dic[r[i]]++;
     }
     if (dic.Count < 3)
     {
         Console.WriteLine(0);
         return;
     }
     long MAX = (long)1e10;
     Heap h = new Heap(0);
     foreach (var item in dic)
     {
         h = meld(h, new Heap(MAX * item.Value + item.Key));
     }
     int[,] ret = new int[n, 3];
     int retnum = 0;
     for (j = 0; ; j++)
     {
         long[] num = new long[3];
         for (i = 0; i < 3; i++)
         {
             num[i] = h.val;
             h = meld(h.r, h.l);
         }
         if (num[2] < MAX) break;
         int[] nums = new int[3];
         for (i = 0; i < 3; i++)
         {
             nums[i] = (int)(num[i] % MAX);
             num[i] -= MAX;
         }
         for (i = 0; i < 3; i++)
         {
             h = meld(h, new Heap(num[i]));
         }
         Array.Sort(nums);
         Array.Reverse(nums);
         for (i = 0; i < 3; i++)
         {
             ret[j, i] = nums[i];
         }
         retnum++;
     }
     Console.WriteLine(retnum);
     for (i = 0; i < retnum; i++)
     {
         Console.WriteLine("{0} {1} {2}", ret[i, 0], ret[i, 1], ret[i, 2]);
     }
 }
开发者ID:pavellevap,项目名称:code_antiplagiat,代码行数:59,代码来源:u2608_140_C_1003639.cs



注:本文中的Heap类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# HeapIndexToken类代码示例发布时间:2022-05-24
下一篇:
C# Health类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap