Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution
- {
- using ll = long long;
- vector<int> g[20003];
- vector<int> ns;
- pair<int, int> dfs(int now, int fa, int v)
- {
- // pair<int, int> means it works or not and the accumulate value from last one mismatch
- int s = ns[now];
- for (auto n : g[now]) {
- if (n == fa)
- continue;
- auto ret = dfs(n, now, v);
- if (ret.first == -1)
- return {-1, 0};
- s += ret.second;
- if (s > v)
- return {-1, 0};
- }
- if (s == v)
- return {0, 0};
- return {0, s};
- }
- bool check(int v)
- {
- auto ret = dfs(0, -1, v);
- if (ret.first == 0)
- return true;
- return false;
- }
- public:
- int componentValue(vector<int> &nums, vector<vector<int>> &edges)
- {
- int maxv = 0;
- ll tot = 0;
- ns = nums;
- for (auto n : nums)
- maxv = max(maxv, n), tot += n;
- for (const auto &e : edges) {
- auto u = e[0], v = e[1];
- g[u].push_back(v), g[v].push_back(u);
- }
- for (int i = maxv; 1ll * i * i <= tot; ++i) {
- if (tot % i == 0 && check(i)) {
- return tot / i - 1;
- }
- }
- return 0;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement