Exemple #1
0
        static void Main(string[] args)
        {
            var result = Precalculations.ReadFromFile(args[0]);

            try
            {
                var answer = KruskalAlgorithm.GetMinimumSpanningTree(result.Item1, result.Item2);
                using (var writer = new StreamWriter(args[1], false))
                {
                    answer = answer.OrderBy(x => x.Start).ToList();
                    int start = -1;
                    foreach (var current in answer)
                    {
                        if (start == current.Start)
                        {
                            writer.Write($"{current.Finish} ({-current.Weight}) ");
                            continue;
                        }
                        start = current.Start;
                        writer.Write($"\n{start}: {current.Finish} ({-current.Weight}) ");
                    }
                }
            }
            catch (UnconnectedGraphException exception)
            {
                Console.Error.WriteLine(exception.Message);
                Environment.Exit(-1);
            }
        }
Exemple #2
0
        /// <summary>
        /// Makes minimum spanning tree
        /// </summary>
        /// <param name="edges">List of graph edges</param>
        /// <param name="nodes">List of graph nodes</param>
        /// <returns>Minimum spanning tree</returns>
        public static List <Edge> GetMinimumSpanningTree(List <Edge> edges, HashSet <int> nodes)
        {
            if (!Precalculations.CheckConnectivity(nodes.Count, edges))
            {
                throw new UnconnectedGraphException();
            }

            var resultList = new List <Edge>();
            var dsu        = new DSU();

            foreach (var node in nodes)
            {
                dsu.MakeSet(node);
            }

            edges = edges.OrderBy(x => x.Weight).ToList();
            foreach (var currentEdge in edges)
            {
                int first  = currentEdge.Start;
                int second = currentEdge.Finish;
                int weight = currentEdge.Weight;

                if (dsu.FindSet(first) != dsu.FindSet(second))
                {
                    resultList.Add(currentEdge);
                    dsu.UnionSet(first, second);
                }
            }

            return(resultList);
        }