Beispiel #1
0
    public static long Solve(int cityCount, List <Edge> edges)
    {
        edges.Sort((e1, e2) => e1.Cost.CompareTo(e2.Cost));
        var  citySets      = new DisjointSets(cityCount);
        long totalEdgeCost = 0;

        for (int e = 0; e < edges.Count; ++e)
        {
            if (!citySets.AreInSameSet(edges[e].SourceCity, edges[e].DestinationCity))
            {
                citySets.UnionSets(edges[e].SourceCity, edges[e].DestinationCity);
                totalEdgeCost += edges[e].Cost;
            }
        }

        return(totalEdgeCost);
    }
Beispiel #2
0
        public void AreInSameSet()
        {
            var disjointSets = new DisjointSets(10);

            for (int i = 0; i < 10; ++i)
            {
                for (int j = 0; j < 10; ++j)
                {
                    if (i != j)
                    {
                        Assert.IsFalse(disjointSets.AreInSameSet(i, j));
                    }
                    else
                    {
                        Assert.IsTrue(disjointSets.AreInSameSet(i, j));
                    }
                }
            }

            disjointSets.UnionSets(0, 3);
            Assert.IsTrue(disjointSets.AreInSameSet(0, 3));
            Assert.IsFalse(disjointSets.AreInSameSet(0, 4));

            disjointSets.UnionSets(1, 4);
            Assert.IsTrue(disjointSets.AreInSameSet(0, 3));
            Assert.IsFalse(disjointSets.AreInSameSet(0, 4));
            Assert.IsTrue(disjointSets.AreInSameSet(1, 4));
            Assert.IsTrue(disjointSets.AreInSameSet(4, 1));

            disjointSets.UnionSets(3, 1);
            Assert.IsTrue(disjointSets.AreInSameSet(0, 4));
            Assert.IsTrue(disjointSets.AreInSameSet(1, 3));
            Assert.IsTrue(disjointSets.AreInSameSet(5, 5));
            Assert.IsFalse(disjointSets.AreInSameSet(1, 5));

            disjointSets.UnionSets(2, 5);
            disjointSets.UnionSets(4, 2);
            disjointSets.UnionSets(6, 7);
            disjointSets.UnionSets(7, 9);
            disjointSets.UnionSets(9, 0);
            disjointSets.UnionSets(2, 6);
            for (int i = 0; i < 10; ++i)
            {
                for (int j = 0; j < 10; ++j)
                {
                    if (i != j)
                    {
                        if (i != 8 && j != 8)
                        {
                            Assert.IsTrue(disjointSets.AreInSameSet(i, j));
                        }
                        else
                        {
                            Assert.IsFalse(disjointSets.AreInSameSet(i, j));
                        }
                    }
                    else
                    {
                        Assert.IsTrue(disjointSets.AreInSameSet(i, j));
                    }
                }
            }
        }