Swift and Python Solutions for Finding the Number of Distinct Parent Nodes and the Maximum Number of Child Nodes
This code aims to find the number of distinct parent nodes and the maximum number of child nodes in a given hierarchical structure. The input consists of sets of integers, where each set represents a group of nodes with a designated parent node. The objective is to determine the count of unique parent nodes and the highest number of child nodes associated with any parent node.
Python Solution
while True:
try:
n = int(input())
sets = [list(map(int, input().split())) for _ in range(n)]
parent, nums = {}, {}
for s in sets:
p = s[0]
nums.setdefault(p, 0)
for i in s:
if i not in parent:
parent[i] = p
nums[p] += 1
else:
while parent[i] != p:
tmp = parent[i]
parent[i] = p
i = tmp
parent[i] = p
if i != p and i in nums:
nums[p] += nums[i]
del nums[i]
print(len(nums.keys()))
print(max(nums.values()))
except:
break
Swift Solution
while true {
guard let n = Int(readLine()!) else {
break
}
var sets = [[Int]]()
for _ in 0..<n {
let set = readLine()!.split(separator: " ").map { Int($0)! }
sets.append(set)
}
var parent = [Int: Int]()
var nums = [Int: Int]()
for s in sets {
let p = s[0]
nums[p, default: 0]
for i in s {
if parent[i] == nil {
parent[i] = p
nums[p, default: 0] += 1
} else {
var tmp = i
while parent[tmp] != p {
let temp = parent[tmp]
parent[tmp] = p
tmp = temp
}
parent[tmp] = p
if tmp != p, let count = nums[tmp] {
nums[p, default: 0] += count
nums.removeValue(forKey: tmp)
}
}
}
}
print(nums.keys.count)
print(nums.values.max()!)
}
Both solutions employ similar logic. They iterate through each set, identifying the parent node and updating the parent-child relationships in the parent dictionary. The nums dictionary keeps track of the number of child nodes associated with each parent. When a node already has a parent, the algorithm efficiently updates the parent-child relationships to ensure accurate counting. Finally, the code outputs the number of distinct parent nodes and the maximum number of child nodes.
This approach leverages dictionaries and efficient loop structures to solve the problem effectively. The Swift solution utilizes optional chaining and default values to handle potential nil values, demonstrating the power of Swift's features.
原文地址: https://www.cveoy.top/t/topic/qsbD 著作权归作者所有。请勿转载和采集!