classSolution: defcomponentValue(self, nums: List[int], edges: List[List[int]]) -> int: g = [[] for _ in nums] for x, y in edges: g[x].append(y) g[y].append(x)
defdfs(x: int, fa: int) -> int: s = nums[x] # 价值 for y in g[x]: if y != fa: res = dfs(y, x) if res < 0: return -1 s += res if s > target: return -1 return s if s < target else0
total = sum(nums) for i inrange(total // max(nums), 1, -1): if total % i == 0: target = total // i if dfs(0, -1) == 0: return i - 1 return0
publicintcomponentValue(int[] nums, int[][] edges) { g = newArrayList[nums.length]; Arrays.setAll(g, e -> newArrayList<>()); for (var e : edges) { intx= e[0], y = e[1]; g[x].add(y); g[y].add(x); } this.nums = nums;
vartotal= Arrays.stream(nums).sum(); varmax= Arrays.stream(nums).max().orElseThrow(); for (vari= total / max; ; --i) if (total % i == 0) { target = total / i; if (dfs(0, -1) == 0) return i - 1; } }
privateintdfs(int x, int fa) { varsum= nums[x]; // 价值 for (var y : g[x]) if (y != fa) { varres= dfs(y, x); if (res < 0) return -1; sum += res; } if (sum > target) return -1; return sum < target ? sum : 0; } }
classSolution { public: intcomponentValue(vector<int> &nums, vector<vector<int>> &edges){ vector<vector<int>> g(nums.size()); for (auto &e : edges) { int x = e[0], y = e[1]; g[x].push_back(y); g[y].push_back(x); }
int target; function<int(int, int)> dfs = [&](int x, int fa) { int sum = nums[x]; // 价值 for (int y : g[x]) if (y != fa) { int res = dfs(y, x); if (res < 0) return-1; sum += res; } if (sum > target) return-1; return sum < target ? sum : 0; };
int total = accumulate(nums.begin(), nums.end(), 0); int mx = *max_element(nums.begin(), nums.end()); for (int i = total / mx;; --i) if (total % i == 0) { target = total / i; if (dfs(0, -1) == 0) return i - 1; } } };
funccomponentValue(nums []int, edges [][]int)int { g := make([][]int, len(nums)) for _, e := range edges { x, y := e[0], e[1] g[x] = append(g[x], y) g[y] = append(g[y], x) }
var target int var dfs func(int, int)int dfs = func(x, fa int)int { sum := nums[x] // 价值 for _, y := range g[x] { if y != fa { res := dfs(y, x) if res < 0 { return-1 } sum += res } } if sum > target { return-1 } if sum == target { return0 } return sum }
total, mx := 0, 0 for _, x := range nums { total += x mx = max(mx, x) } for i := total / mx; ; i-- { if total%i == 0 { target = total / i if dfs(0, -1) == 0 { return i - 1 } } } }
funcmin(a, b int)int { if b < a { return b }; return a } funcmax(a, b int)int { if b > a { return b }; return a }
复杂度分析
时间复杂度:O(n\cdot d(s)),其中 n 为 nums 的长度,s 为所有 nums}[i] 的和,d(s) 为 s 的因子个数。根据本题的数据范围,d(s)\le 240,s=720720 时取等号。