from math import ceil N = 9 arr = [i for i in range(N)] nodes = set((i, i + 1) for i in range(N - 1)) print("Initial array:", arr) print("Initial edges:", nodes) def func(start, end): if end - start <= 3: # If the segment is small enough, connect all pairs directly. for i in range(start, end + 1): for j in range(i + 1, end + 1): nodes.add((i, j)) return [start, end] n = end - start + 1 k = int(ceil(n**0.5)) # Calculate the number of segments based on sqrt(n) size = ceil(n / k) # Ensure the size covers all elements to the end. last_end = start - 1 results = [] for i in range(k): new_start = last_end + 1 new_end = new_start + size - 1 if new_end >= end: # Prevent the segment from exceeding the bounds. new_end = end results.extend(func(new_start, new_end)) last_end = new_end if new_end == end: break # Connecting all results segments fully (could be optimized if needed) for i in range(len(results)): for j in range(i + 1, len(results)): nodes.add((results[i], results[j])) return results func(0, N - 1) print("Edges after processing:", nodes) print("No. of new edges added:", len(nodes) - (N - 1))
Standard input is empty
Initial array: [0, 1, 2, 3, 4, 5, 6, 7, 8] Initial edges: {(0, 1), (1, 2), (3, 4), (2, 3), (6, 7), (4, 5), (5, 6), (7, 8)} Edges after processing: {(3, 4), (0, 2), (0, 5), (0, 8), (2, 5), (2, 8), (6, 8), (4, 5), (5, 6), (3, 6), (0, 1), (1, 2), (6, 7), (3, 5), (3, 8), (5, 8), (0, 3), (0, 6), (2, 3), (2, 6), (7, 8)} No. of new edges added: 13