public int RemoveStones(int[][] stones) { DisjointSetUnion dsu = new DisjointSetUnion(); // var printSet = dsu.PrintSets(stones); foreach (int[] stone in stones) { dsu.MakeSet(new Point(stone[0], stone[1])); } for (int i = 0; i < stones.Length - 1; i++) { Point p1 = new Point(stones[i][0], stones[i][1]); for (int j = i + 1; j < stones.Length; j++) { Point p2 = new Point(stones[j][0], stones[j][1]); if (p1.X == p2.X || p1.Y == p2.Y) { dsu.Union(p1, p2); } } } HashSet <Point> seenSet = new HashSet <Point>(); for (int i = 0; i < stones.Length; i++) { seenSet.Add(dsu.Find(new Point(stones[i][0], stones[i][1]))); } return(stones.Length - seenSet.Count); }
static void Main(string[] args) { var counts = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); var varCount = counts[0]; var equalsCount = counts[1]; var unEqualsCount = counts[2]; var analyzer = new DisjointSetUnion(varCount); for (int i = 0; i < varCount; i++) { analyzer.MakeSet(i); } for (int i = 0; i < equalsCount; i++) { var equalPair = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); analyzer.Union(equalPair[0] - 1, equalPair[1] - 1); } for (int i = equalsCount; i < equalsCount + unEqualsCount; i++) { var unEqualPair = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); if (analyzer.Find(unEqualPair[0] - 1) == analyzer.Find(unEqualPair[1] - 1)) { Console.WriteLine("0"); return; } } Console.WriteLine("1"); Console.ReadKey(); }
public override int[] GetPath(int n, IMeasure measure) { var edges = new List<Edge>((n * (n - 1)) % 2); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { edges.Add(new Edge(i, j)); } } var set = new DisjointSetUnion<int>(); for (int i = 0; i < n; i++) { set.MakeSet(i); } var result = new List<Edge>(n - 1); var r = new int[n]; foreach (var edge in edges.OrderBy(a => measure[a.From, a.To])) { if (r[edge.From] < 2 && r[edge.To] < 2 && set.FindSet(edge.From) != set.FindSet(edge.To)) { result.Add(edge); set.UnionSets(edge.From, edge.To); r[edge.From]++; r[edge.To]++; } } return GetResult(n, result); }
public void ArgumentOutOfRangeInLeaderOfAndSizeOfTest([Values(-1, 2)] int v) { var dsu = new DisjointSetUnion(2); Assert.Throws <ArgumentOutOfRangeException>(() => dsu.LeaderOf(v)); Assert.Throws <ArgumentOutOfRangeException>(() => dsu.SizeOf(v)); }
public void ArgumentOutOfRangeInMergeAndIsSameTest(int u, int v) { var dsu = new DisjointSetUnion(2); Assert.Throws <ArgumentOutOfRangeException>(() => dsu.Merge(u, v)); Assert.Throws <ArgumentOutOfRangeException>(() => dsu.IsSame(u, v)); }
public void DisjointSetUnionMustWork() { var rnd = new Random(123); for (int times = 0; times < 100; times++) { int n = rnd.Next(50) + 1; var dsu = new DisjointSetUnion(n); var naiveDsu = new DisjointSetUnionNaive(n); for (int ops = 0; ops < 100; ops++) { int a = rnd.Next(n), b = rnd.Next(n); if (rnd.Next(2) == 0) { Assert.AreEqual(naiveDsu.InOneSet(a, b), dsu.InOneSet(a, b)); } else { Assert.AreEqual(naiveDsu.Join(a, b), dsu.Join(a, b)); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Assert.AreEqual(naiveDsu.InOneSet(i, j), dsu.InOneSet(i, j)); } } } }
public void InitializeTest() { Assert.DoesNotThrow(() => _ = new DisjointSetUnion(2)); Assert.Throws <ArgumentOutOfRangeException>(() => _ = new DisjointSetUnion(-1)); Assert.That(new DisjointSetUnion(0).Length, Is.Zero); Assert.That(new DisjointSetUnion(10).Length, Is.EqualTo(10)); }
public VideoCloudPoints(string videoPath, int frameCount) { _frameCount = frameCount; _videoPath = videoPath; _vectorOfKeyPoints = new VectorOfKeyPoint[frameCount]; _disjointSetUnion = new DisjointSetUnion(frameCount); }
public void TableUnionCorrect(int varCount, int equalsCount, int unEqualsCount, string[] relations, int expResult) { // Arrange var result = 1; // Act var analyzer = new DisjointSetUnion(varCount); for (int i = 0; i < varCount; i++) { analyzer.MakeSet(i); } for (int i = 0; i < equalsCount; i++) { var equalPair = relations[i].Split(' ').Select(int.Parse).ToArray(); analyzer.Union(equalPair[0] - 1, equalPair[1] - 1); } for (int i = equalsCount; i < equalsCount + unEqualsCount; i++) { var unEqualPair = relations[i].Split(' ').Select(int.Parse).ToArray(); if (analyzer.Find(unEqualPair[0] - 1) == analyzer.Find(unEqualPair[1] - 1)) { result = 0; } } // Assert Assert.AreEqual(expResult, result); }
public void SameLeaderTest() { var dsu = new DisjointSetUnion(3); dsu.Merge(0, 1); dsu.Merge(0, 2); Assert.That(dsu.Merge(1, 2), Is.Zero); }
public void InitiallyDisjoint() { DisjointSetUnion dsu = new DisjointSetUnion(10); for (int i = 0; i < 10; ++i) { Assert.AreEqual(i, dsu.Find(i)); } }
public void SimpleTest() { var dsu = new DisjointSetUnion(2); var x = dsu.Merge(0, 1); Assert.That(dsu.LeaderOf(0), Is.EqualTo(x)); Assert.That(dsu.LeaderOf(1), Is.EqualTo(x)); Assert.That(dsu.IsSame(0, 1), Is.True); Assert.That(dsu.SizeOf(0), Is.EqualTo(2)); }
public TableSet(Table[] data) { _dsu = new DisjointSetUnion(data.Length); _data = data; for (int i = 0; i < data.Length; i++) { _dsu.MakeSet(i); UpdateMax(_data[i].RowsCount); } }
public void LineReverseTest() { const int n = 500000; var dsu = new DisjointSetUnion(n); for (var i = n - 2; i >= 0; i--) { dsu.Merge(i, i + 1); } Assert.That(dsu.SizeOf(0), Is.EqualTo(n)); Assert.That(dsu.GetGroups().Count, Is.EqualTo(1)); }
public void SimpleUnion() { DisjointSetUnion dsu = new DisjointSetUnion(10); dsu.Unite(0, 1); Assert.IsTrue(dsu.Same(0, 1)); dsu.Unite(2, 3); Assert.IsTrue(dsu.Same(2, 3)); dsu.Unite(4, 5); Assert.IsTrue(dsu.Same(4, 5)); }
public IList <IList <string> > AccountsMerge(IList <IList <string> > accounts) { var dsu = new DisjointSetUnion(10001); var emailIds = new Dictionary <string, int>(); var emailNames = new Dictionary <string, string>(); var id = 0; foreach (var account in accounts) { var name = account[0]; for (var i = 1; i < account.Count; ++i) { var email = account[i]; emailNames[email] = name; if (!emailIds.ContainsKey(email)) { ++id; emailIds.Add(email, id); } dsu.Union(emailIds[account[1]], emailIds[email]); } } var res = new Dictionary <int, IList <string> >(); foreach (var email in emailNames.Keys) { var emailId = dsu.Find(emailIds[email]); if (!res.TryGetValue(emailId, out var account)) { account = new List <string>(); res.Add(emailId, account); } account.Add(email); } foreach (List <string> account in res.Values) { account.Sort((string left, string right) => string.CompareOrdinal(left, right)); account.Insert(0, emailNames[account[0]]); } return(res.Values.ToList()); }
//traversal to find duplicate /* private bool DFS(int start, int end, Dictionary<int, IList<int>> path, Dictionary<int, bool> visited) * { * if (start == end && visited[end]) * return true; * * visited[start] = true; * if (!path.ContainsKey(start)) * return false; * * int vertex = path[start].Count; * * for ( int i = 0; i < vertex; i++) * { * bool result = DFS(path[start][i], end, path, visited); * if (result) * return result; * } * return false; * } * * public int[] FindRedundantConnection(int[][] edges) * { * Dictionary<int, int> nodeDegree = new Dictionary<int, int>(); * int rowCount = edges.Length; * * int[] result = new int[2]; * * Dictionary<int, bool> visited = new Dictionary<int, bool>(); * * Dictionary<int, IList<int>> dictMatrix = new Dictionary<int, IList<int>>(); * * for (int i = 0; i < rowCount; i++) * { * if (!visited.ContainsKey(edges[i][0])) * visited.Add(edges[i][0], false); * if (!visited.ContainsKey(edges[i][1])) * visited.Add(edges[i][1], false); * * if (nodeDegree.ContainsKey(edges[i][0])) * nodeDegree[edges[i][0]]++; * else * nodeDegree.Add(edges[i][0], 1); * * if (nodeDegree.ContainsKey(edges[i][1])) * nodeDegree[edges[i][1]]++; * else * nodeDegree.Add(edges[i][1], 1); * * if (dictMatrix.ContainsKey(edges[i][0])) * dictMatrix[edges[i][0]].Add(edges[i][1]); * else * dictMatrix[edges[i][0]] = new List<int>() { edges[i][1] }; * * } * * Dictionary<int, bool> visitedCopy1 = new Dictionary<int, bool>(visited); * for (int i = rowCount - 1; i >= 0; i--) * { * if (nodeDegree[edges[i][1]] == 1 || nodeDegree[edges[i][0]] == 1) * continue; * foreach(var entry in visitedCopy1) * visited[entry.Key]= false; * Dictionary<int, bool> visitedCopy = new Dictionary<int, bool>(visitedCopy1); * if (DFS(edges[i][0], edges[i][1], dictMatrix, visitedCopy)) * return new int[] { edges[i][0], edges[i][1] }; * } * * return result; * }*/ //DSU public int[] FindRedundantConnection(int[][] edges) { DisjointSetUnion dsu = new DisjointSetUnion(); int[] result = new int[2]; foreach (int[] edge in edges) { if (dsu.Find(edge[0]) == dsu.Find(edge[1])) { result[0] = edge[0]; result[1] = edge[1]; } dsu.Union(edge[0], edge[1]); } return(result); }
public int MakeConnected(int n, int[][] connections) { var dsu = new DisjointSetUnion(n); var segments = new Dictionary <int, int>(); var edges = new Dictionary <int, int>(); foreach (var c in connections) { dsu.Union(c[0], c[1]); } for (var i = 0; i < n; ++i) { var parent = dsu.Find(i); if (!segments.TryGetValue(parent, out var cnt)) { cnt = 0; } segments[parent] = cnt + 1; } foreach (var c in connections) { var parent = dsu.Find(c[0]); if (!edges.TryGetValue(parent, out var cnt)) { cnt = 0; } edges[parent] = cnt + 1; } var freeCabels = 0; foreach (var segment in segments) { var minCabelsRequired = segment.Value - 1; var actualCabels = edges.TryGetValue(segment.Key, out var segmentEdges) ? segmentEdges : 0; freeCabels += minCabelsRequired > actualCabels ? 0 : actualCabels - minCabelsRequired; } return(freeCabels < segments.Count - 1 ? -1 : segments.Count - 1); }
public int NumIslands(char[][] grid) { if (null == grid || 0 == grid.Length) { return(0); } var connectedComponentsCount = 0; var rows = grid.Length; var cols = grid[0].Length; var dsu = new DisjointSetUnion(1 + rows * cols); for (var row = 0; rows > row; ++row) { for (var col = 0; cols > col; ++col) { if ('1' == grid[row][col]) { if (rows > 1 + row && '1' == grid[1 + row][col]) { dsu.union(cols * (1 + row) + col, cols * row + col); } if (cols > 1 + col && '1' == grid[row][1 + col]) { dsu.union(cols * row + col + 1, cols * row + col); } } else { dsu.union(cols * row + col, rows * cols); } } } for (var i = 0; rows *cols > i; ++i) { if (i == dsu.find(i)) { ++connectedComponentsCount; } } return(connectedComponentsCount); }
public long Kruskal() { long res = 0; DisjointSetUnion disjoin = new DisjointSetUnion(NumVertices); Vector <Pair <int, Pair <int, int> > > P = ToVectorPair(adjMatrix); P.Sort(); foreach (var item in P) { int x = item.Second.First; int y = item.Second.Second; if (disjoin.Join(x, y)) { res += item.First; } } return(res); }
public static long RunSequentialKruskal(this Graph g) { var dsu = new DisjointSetUnion(g.VerticesNumber); var edges = g.Edges.ToList(); edges.Sort(); long result = 0; foreach (var edge in edges) { if (dsu.Find(edge.start) != dsu.Find(edge.end)) { result += edge.weight; dsu.Union(edge.start, edge.end); } } return(result); }
public void ComplexUnion() { DisjointSetUnion dsu = new DisjointSetUnion(10); dsu.Unite(0, 1); dsu.Unite(2, 3); dsu.Unite(5, 6); dsu.Unite(7, 8); dsu.Unite(6, 7); dsu.Unite(0, 2); Assert.IsTrue(dsu.Same(0, 1)); Assert.IsTrue(dsu.Same(2, 3)); Assert.IsTrue(dsu.Same(0, 2)); Assert.IsTrue(dsu.Same(8, 6)); Assert.IsFalse(dsu.Same(0, 7)); dsu.Unite(0, 6); Assert.IsTrue(dsu.Same(0, 7)); }
public static void Solve() { var NQ = Console.ReadLine().Split(" ").Select(int.Parse).ToArray(); var(N, Q) = (NQ[0], NQ[1]); var dsu = new DisjointSetUnion(N); for (var i = 0; i < Q; i++) { var TUV = Console.ReadLine().Split(" ").Select(int.Parse).ToArray(); var(t, u, v) = (TUV[0], TUV[1], TUV[2]); if (t == 0) { dsu.Merge(u, v); } else { Console.WriteLine(dsu.IsSame(u, v) ? 1 : 0); } } }
public int FindCircleNum(int[][] M) { var set = new HashSet <int>(); var dsu = new DisjointSetUnion(M.Length); for (var i = 0; i < M.Length; ++i) { for (var j = 0; j < M[i].Length; ++j) { if (M[i][j] == 1) { dsu.Union(i, j); } } } for (var i = 0; i < M.Length; ++i) { set.Add(dsu.Find(i)); } return(set.Count); }
public int NumSimilarGroups(string[] A) { var dsu = new DisjointSetUnion(A.Length); for (var i = 0; i < A.Length; ++i) { for (var j = i + 1; j < A.Length; ++j) { if (AreSimilar(A[i], A[j])) { dsu.Union(i, j); } } } var set = new HashSet <int>(); for (var i = 0; i < A.Length; ++i) { set.Add(dsu.Find(i)); } return(set.Count); }
public static long RunParallelThreadsKruskal(this Graph g) { var dsu = new DisjointSetUnion(g.VerticesNumber); var edges = new List <Graph.Edge>(); var chunkSize = g.EdgesNumber; if (g.EdgesNumber > Environment.ProcessorCount) { chunkSize = g.EdgesNumber / Environment.ProcessorCount; } var chunksNumber = g.EdgesNumber / chunkSize; var chunks = new List <Graph.Edge> [chunksNumber]; var tasks = new List <Task>(); var start = new int[chunksNumber]; for (int i = 0, chunk = chunkSize; i < g.EdgesNumber; i += chunk) { if (i + 2 * chunk > g.EdgesNumber) { chunk = g.EdgesNumber - i; } chunks[i / chunkSize] = new List <Graph.Edge>(); for (var j = i; j < i + chunk; ++j) { chunks[i / chunkSize].Add(g.Edges[j]); } var i1 = i / chunkSize; tasks.Add(Task.Run(() => chunks[i1].Sort())); } Task.WaitAll(tasks.ToArray()); while (edges.Count != g.EdgesNumber) { var cur = new Graph.Edge(); var id = -1; for (var i = 0; i < chunks.Length; ++i) { if (start[i] < chunks[i].Count && (id == -1 || chunks[i][start[i]].weight < cur.weight)) { id = i; cur = chunks[i][start[i]]; } } edges.Add(cur); ++start[id]; } long result = 0; foreach (var edge in edges) { if (dsu.Find(edge.start) != dsu.Find(edge.end)) { result += edge.weight; dsu.Union(edge.start, edge.end); } } return(result); }
// CONSTRUCTORS public RandomizedKruskalsAlgorithm() : base() { sets = new DisjointSetUnion <CellIndices>(); listSets = new List <CellIndices>(100); }
public Graph(int totalNodes) { _nodesTaken = new DisjointSetUnion(totalNodes); edges = new List <Tuple <int, int, int> >(); }