Ejemplo n.º 1
0
        public int LargestComponentSize(int[] A)
        {
            int maxValue = A.Max();
            var uf       = new UnionFind(maxValue + 1);

            var numFactorMap = new Dictionary <int, int>();

            foreach (int num in A)
            {
                var primeFactors = PrimeDecompose(num);

                numFactorMap[num] = primeFactors[0];
                for (int i = 0; i < primeFactors.Count - 1; ++i)
                {
                    uf.Union(primeFactors[i], primeFactors[i + 1]);
                }
            }

            // count the size of group one by one
            int maxGroupSize = 0;
            var groupCount   = new Dictionary <int, int>();

            foreach (int num in A)
            {
                var groupId = uf.Find(numFactorMap[num]);
                groupCount.TryGetValue(groupId, out int count);
                groupCount[groupId] = count + 1;

                maxGroupSize = Math.Max(maxGroupSize, count + 1);
            }

            return(maxGroupSize);
        }
Ejemplo n.º 2
0
        public int MaxAreaOfIsland(int[][] grid)
        {
            var uf = new UnionFind(grid);

            int m = grid.Length;
            int n = grid[0].Length;

            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if (grid[i][j] == 1)
                    {
                        if (i - 1 >= 0 && grid[i - 1][j] == 1)
                        {
                            uf.Union(i * n + j, (i - 1) * n + j);
                        }
                        if (i + 1 < m && grid[i + 1][j] == 1)
                        {
                            uf.Union(i * n + j, (i + 1) * n + j);
                        }
                        if (j - 1 >= 0 && grid[i][j - 1] == 1)
                        {
                            uf.Union(i * n + j, i * n + j - 1);
                        }
                        if (j + 1 < n && grid[i][j + 1] == 1)
                        {
                            uf.Union(i * n + j, i * n + j + 1);
                        }
                    }
                }
            }
            return(uf.RankMax());
        }
Ejemplo n.º 3
0
        public double[] CalcEquation(IList <IList <string> > equations, double[] values, IList <IList <string> > queries)
        {
            var uf = new UnionFind();

            for (int i = 0; i < equations.Count; i++)
            {
                uf.Union(equations[i][0], equations[i][1], values[i]);
            }

            var result = new double[queries.Count];

            for (int i = 0; i < queries.Count; i++)
            {
                var x = queries[i][0];
                var y = queries[i][1];
                if (uf.Exist(x) && uf.Exist(y))
                {
                    var px = uf.Find(x);
                    var py = uf.Find(y);

                    if (px.ParentIndex == py.ParentIndex)
                    {
                        result[i] = px.Value / py.Value;
                        continue;
                    }
                }

                result[i] = -1;
            }

            return(result);
        }
Ejemplo n.º 4
0
        int GetMinCostToConstruct(int numTotalAvailableCities,
                                  int numTotalAvailableRoads,
                                  List <List <int> > roadsAvailable,
                                  int numNewRoadsConstruct,
                                  List <List <int> > costNewRoadsConstruct
                                  )
        {
            if (numTotalAvailableCities < 2 || numTotalAvailableRoads >= numTotalAvailableCities - 1)
            {
                return(0);
            }
            UnionFind uf = new UnionFind(numTotalAvailableCities);

            int avblRdCnt = 0;

            foreach (List <int> r in roadsAvailable)
            {
                int c1 = r[0];
                int c2 = r[1];

                if (!uf.Find(c1, c2))
                {
                    uf.Union(c1, c2);
                    avblRdCnt++;
                }
            }
            HashSet <Connetction> connection_hs = ListToHashsetConverter(costNewRoadsConstruct);

            ArrayList mst = new ArrayList();

            connection_hs.OrderBy(x => x.Cost);
            while (connection_hs.Count > 0 && mst.Count + avblRdCnt < numTotalAvailableCities - 1)
            {
                Connetction temp = connection_hs.FirstOrDefault();
                int         c1   = temp.City1;
                int         c2   = temp.City2;
                if (!uf.Find(c1, c2))
                {
                    uf.Union(c1, c2);
                    mst.Add(temp);
                }
                connection_hs.Remove(temp);
            }
            if (mst.Count + avblRdCnt < numTotalAvailableCities - 1)
            {
                return(-1);
            }
            int sum = 0;

            foreach (Connetction c in mst)
            {
                sum += c.Cost;
            }
            return(sum);
        }
Ejemplo n.º 5
0
 public static void Main()
 {
     int[,] a = new int[5, 2] {
         { 3, 4 },    /*  initializers for row indexed by 0 */
         { 1, 2 },    /*  initializers for row indexed by 1 */
         { 2, 4 },    /*  initializers for row indexed by 2 */
         { 3, 5 },
         { 2, 5 }
     };
     a = new int[, ] {
         { 16, 25 }, { 7, 9 }, { 3, 24 }, { 10, 20 }, { 15, 24 }, { 2, 8 }, { 19, 21 }, { 2, 15 }, { 13, 20 }, { 5, 21 }, { 7, 11 }, { 6, 23 }, { 7, 16 }, { 1, 8 }, { 17, 20 }, { 4, 19 }, { 11, 22 }, { 5, 11 }, { 1, 16 }, { 14, 20 }, { 1, 4 }, { 22, 23 }, { 12, 20 }, { 15, 18 }, { 12, 16 }
     };
     var obj = new UnionFind();
     var x   = obj.FindRedundantConnection(a);
 }
Ejemplo n.º 6
0
        public IList <IList <string> > AccountsMerge(IList <IList <string> > accounts)
        {
            var uf          = new UnionFind();
            var emailToName = new Dictionary <string, string>();
            var emailToId   = new Dictionary <string, int>();

            var id = 0;

            foreach (var account in accounts)
            {
                var name = string.Empty;
                foreach (var str in account)
                {
                    if (name == string.Empty)
                    {
                        name = str;
                        continue;
                    }

                    emailToName[str] = name;
                    if (!emailToId.ContainsKey(str))
                    {
                        emailToId[str] = id++;
                    }
                    uf.Union(emailToId[account[1]], emailToId[str]);
                }
            }

            var map = new Dictionary <int, IList <string> >();

            foreach (var email in emailToName.Keys)
            {
                var index = uf.Find(emailToId[email]);
                if (!map.ContainsKey(index))
                {
                    map[index] = new List <string>();
                }
                map[index].Add(email);
            }

            return(map.Values.Select(list =>
            {
                IList <string> temp = list.OrderBy(e => e, StringComparer.Ordinal).ToList();
                temp.Insert(0, emailToName[list[0]]);
                return temp;
            }).ToList());
        }
Ejemplo n.º 7
0
        public int RemoveStones(int[][] stones)
        {
            var uf = new UnionFind(BOARD_SIZE * 2);

            foreach (var stone in stones)
            {
                uf.Union(stone[0], stone[1] + BOARD_SIZE);
            }

            var set = new HashSet <int>();

            foreach (var stone in stones)
            {
                set.Add(uf.FindParent(stone[0]));
            }
            return(stones.Length - set.Count);
        }
Ejemplo n.º 8
0
        public Kruskal(EdgeWeightedGraph <TVertex, TWeight> graph, WeightedEdge <TVertex, TWeight> initialMst)
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }

            var edges = new MinPriorityQueue <WeightedEdge <TVertex, TWeight> >(graph.EdgeNumber);

            foreach (var edge in graph.Edges)
            {
                if (!edge.Equals(initialMst))
                {
                    edges.Add(edge);
                }
            }

            var mst = new UnionFind <TVertex>(graph.Vertices);

            MinimumSpanningTree = new List <WeightedEdge <TVertex, TWeight> >(graph.VertexNumber - 1);
            if (initialMst != null)
            {
                var vertex1 = initialMst.GetVertex();
                var vertex2 = initialMst.GetTheOtherVertex(vertex1);
                mst.Union(vertex1, vertex2);
                MinimumSpanningTree.Add(initialMst);
            }

            while (!edges.IsEmpty && MinimumSpanningTree.Count < graph.VertexNumber - 1)
            {
                var edge    = edges.DeleteMin();
                var vertex1 = edge.GetVertex();
                var vertex2 = edge.GetTheOtherVertex(vertex1);
                if (!mst.IsConnected(vertex1, vertex2))
                {
                    mst.Union(vertex1, vertex2);
                    MinimumSpanningTree.Add(edge);
                }
            }

            if (MinimumSpanningTree.Count < graph.VertexNumber - 1)
            {
                throw new ArgumentException();
            }
        }
Ejemplo n.º 9
0
        public string SmallestEquivalentString(string A, string B, string S)
        {
            var uf = new UnionFind(26);

            for (int i = 0; i < A.Length; i++)
            {
                uf.Union(A[i] - 'a', B[i] - 'a');
            }

            var sb = new StringBuilder(S.Length);

            foreach (var ch in S)
            {
                sb.Append((char)(uf.Find(ch - 'a') + 'a'));
            }

            return(sb.ToString());
        }
Ejemplo n.º 10
0
        public int MaximumMinimumPath(int[][] A)
        {
            int N = A.Length;
            int M = A[0].Length;

            var directions = new List <(int dr, int dc)>()
            {
                (1, 0), (-1, 0), (0, 1), (0, -1)
            };
            var uf      = new UnionFind(N * M);
            var visited = new bool[N, M];

            var points = new List <(int r, int c, int val)>(N * M);

            for (int i = 0; i < N; i++)
            {
                for (int j = 0; j < M; j++)
                {
                    points.Add((i, j, A[i][j]));
Ejemplo n.º 11
0
        public int EarliestAcq(int[][] logs, int N)
        {
            if (logs.Length < N - 1)
            {
                return(-1);
            }
            logs = logs.OrderBy(log => log[0]).ToArray();

            var uf = new UnionFind(N);

            foreach (var item in logs)
            {
                uf.Union(item[1], item[2]);
                if (uf.Count == 1)
                {
                    return(item[0]);
                }
            }

            return(-1);
        }