Пример #1
0
    List <Edge> PrimsMST(Graph g)
    {
        Dictionary <int, Edge> map   = new Dictionary <int, Edge>();
        MinHeapMap <Vertex>    queue = new MinHeapMap <Vertex>();

        List <Edge> mst = new List <Edge>();

        List <Vertex> allVertex = new List <Vertex>(g.allVertex.Values);
        Vertex        start     = allVertex[0];

        foreach (Vertex v in allVertex)
        {
            queue.Enqueue(v, int.MaxValue);
        }

        queue.UpdatePriority(start, 0);
        HashSet <Vertex> visited = new HashSet <Vertex>();

        visited.Add(start);


        while (queue.Count() > 0)
        {
            Vertex cur = queue.Dequeue();
            visited.Add(cur);
            if (map.ContainsKey(cur.id))
            {
                mst.Add(map[cur.id]);
            }

            foreach (Edge e in cur.adjEdge)
            {
                Vertex adj = g.GetAdjVertexForEdge(cur, e);
                if (!visited.Contains(adj) && queue.GetPriority(adj) > e.weight)
                {
                    queue.UpdatePriority(adj, e.weight);
                    if (!map.ContainsKey(adj.id))
                    {
                        map.Add(adj.id, e);
                    }
                    else
                    {
                        map[adj.id] = e;
                    }
                }
            }
        }
        return(mst);
    }
Пример #2
0
    public static void Main5(string[] args)
    {
        MinHeapMap <string> pq = new MinHeapMap <string>();

        pq.Enqueue("Bob", 5);
        pq.Enqueue("Rob", 10);
        pq.Enqueue("Mike", 6);
        pq.Enqueue("Tina", 3);
        pq.Enqueue("Andy", 2);
        pq.Enqueue("Judy", 9);

        pq.UpdatePriority("Tina", 10);
        pq.UpdatePriority("Rob", 5);

        int ct = 6;

        while (ct > 0)
        {
            Console.WriteLine(pq.Dequeue());
            ct--;
        }
        Console.WriteLine();
    }