[InterviewBit] Delete Edge!

Delete Edge!

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <bits/stdc++.h>
long long mod = 1e9 + 7;
long long dfs1(vector<int>& A, vector<long long>& B, int u, int par, vector<vector<long long>>& adj) {
B[u] += A[u];
for(auto v : adj[u]) {
if(v == par) continue;
B[u] += dfs1(A,B,v,u,adj);
}
return B[u];
}

int Solution::deleteEdge(vector<int> &A, vector<vector<int> > &B) {
vector<long long> sum(A.size());
vector<vector<long long>> adj(A.size());
for(int i = 0; i < B.size(); i++) {
auto u = B[i][0], v = B[i][1];
u -= 1, v -= 1;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs1(A,sum,0,-1,adj);
long long res = 0, every = accumulate(begin(A), end(A), 0ll);
for(int i = 0; i < sum.size(); i++) {
res = max(res, (every - sum[i]) * sum[i]);
}
return res % mod;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/03/PS/interviewbit/delete-edge/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.