bool Solve() { var I = G; N = I[0]; Q = I[1]; l = new int[Q]; r = new int[Q]; d = new int[Q]; var uf = new UnionFindTree(N); x = new int[N]; done = new bool[N]; g = new List <Edge> [N]; for (var i = 0; i < N; i++) { g[i] = new List <Edge>(); } for (var i = 0; i < Q; i++) { I = G; l[i] = I[0] - 1; r[i] = I[1] - 1; d[i] = I[2]; g[l[i]].Add(new Edge(r[i], -d[i])); g[r[i]].Add(new Edge(l[i], +d[i])); uf.UniteCategory(l[i], r[i]); } for (var i = 0; i < N; i++) { if (!done[uf.GetRootOf(i)] && !DFS(uf.GetRootOf(i), 0)) { return(false); } } return(true); }
/// <summary> /// メイン処理をここに書く /// </summary> void SolveOne() { int n = sc.nextInt(); int k = sc.nextInt(); int l = sc.nextInt(); int[] p = new int[k]; int[] q = new int[k]; int[] r = new int[l]; int[] s = new int[l]; int[] ans = new int[n]; UnionFindTree road = new UnionFindTree(n); UnionFindTree rail = new UnionFindTree(n); for (int i = 0; i < k; i++) { p[i] = sc.nextInt() - 1; q[i] = sc.nextInt() - 1; road.UniteCategory(p[i], q[i]); } for (int i = 0; i < l; i++) { r[i] = sc.nextInt() - 1; s[i] = sc.nextInt() - 1; rail.UniteCategory(r[i], s[i]); } string[] ls = new string[n]; HashMap <string, int> map = new HashMap <string, int>(); for (int i = 0; i < n; i++) { ls[i] = road.GetRootOf(i).ToString() + " " + rail.GetRootOf(i).ToString(); map[ls[i]]++; } for (int i = 0; i < n; i++) { ans[i] = map[ls[i]]; } Console.WriteLine(String.Join(" ", ans)); }
void Solve() { var I = G; int N = I[0], M = I[1]; var p = G.Select(i => i - 1).ToArray(); var uf = new UnionFindTree(N); for (var i = 0; i < M; i++) { I = G; uf.UniteCategory(I[0] - 1, I[1] - 1); } var ans = 0; var cmps = new Dictionary <int, HashSet <int> >(); for (var i = 0; i < N; i++) { var r = uf.GetRootOf(i); if (!cmps.ContainsKey(r)) { cmps[r] = new HashSet <int> { i } } ; cmps[r].Add(i); } foreach (var s in cmps.Values) { foreach (var i in s) { if (s.Contains(p[i])) { ans++; } } } WriteLine(ans); } }
public override IEnumerable <object> Solve(TextReader inputStream) { var townsCount = inputStream.ReadInt(); var plan = inputStream.ReadIntArray().Select(i => i - 1).ToArray(); int baseRoads = 0; var unionFind = new UnionFindTree(townsCount); for (int town = 0; town < plan.Length; town++) { if (plan[town] >= 0 && !unionFind.IsInSameGroup(town, plan[town])) { unionFind.Unite(town, plan[town]); baseRoads++; } } var parents = new int[townsCount]; for (int i = 0; i < parents.Length; i++) { parents[i] = unionFind.GetRootOf(i); } var roots = parents.Distinct().ToArray(); var dictionary = new Dictionary <int, int>(); foreach (var group in parents.GroupBy(i => i)) { dictionary[group.Key] = group.Count(); } for (int i = 0; i < roots.Length; i++) { for (int j = i + 1; j < roots.Length; j++) { } } }