예제 #1
0
        // 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 PriorityQueue<int, int>((e1, e2) => -e1.CompareTo(e2));

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

            // return value
            int ret = 0;
            int edgeCount = 0;

            while (edgeCount < verticeCount - hospitals.Count())
            {
                edgeCount += 1;

                // edge nearest to 'hospital'

                var min = distances.DequeueWithPriority();
                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))
                    ret += weight;

                // update the priorities of all edges incident on the vertex
                // we've just added

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

                    var priority = distances.PriorityOrDefault(v2, int.MaxValue);

                    if (priority > weight + adj.Item2)
                        distances.Rekey(v2, weight + adj.Item2);
                }
            }

            return ret;
        }