コード例 #1
0
        static void Main(string[] args)
        {
            MinHeap <int> heap = new MinHeap <int>();

            heap.Add(10);
            heap.Add(16);
            heap.Add(30);
            heap.Add(20);
            heap.Add(50);
            heap.Add(15);
            heap.Add(8);

            while (!heap.IsEmpty)
            {
                Console.Write(heap.Pop() + " ");
            }

            EndProgram();
        }
コード例 #2
0
        /// <summary>
        /// Find the shortest distance between this node and all the others.
        /// </summary>
        /// <param name="nodeid">Start node</param>
        public void FindShortest(int nodeid)
        {
            Nodes[nodeid].Dist = 0;
            bool[]         finished = new bool[Nodes.Length];
            MinHeap <Node> heap     = new MinHeap <Node>(Nodes);

            while (heap.Count > 0)
            {
                Node node = heap.Pop();
                if (node.Dist == Node.NoConnection)
                {
                    break;                                 // no more connected nodes
                }
                finished[node.Id] = true;
                foreach (Edge edge in node.Edges)
                {
                    Node n2 = (edge.N1.Id == node.Id) ? edge.N2 : edge.N1;
                    if (finished[n2.Id])
                    {
                        continue;
                    }

                    int dist = node.Dist + edge.Weight;
                    if (dist < n2.Dist)
                    {
                        n2.Dist = dist;
                    }
                }
                heap.Heapify();
            }

            for (int idx = 1; idx <= nNodes; idx++)
            {
                Node node = Nodes[idx];
                if (idx != nodeid)
                {
                    Console.Write("{0} ", (node.Dist != Node.NoConnection) ? node.Dist : -1);
                }
            }
            Console.WriteLine();
        }