-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp
More file actions
84 lines (72 loc) · 2.19 KB
/
cpp
File metadata and controls
84 lines (72 loc) · 2.19 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
#include <cstring> // for memset
using namespace std;
void dfs(int node, int parent, int depth, vector<vector<int>>& adjList, vector<int>& depths) {
depths[node] = depth;
for (int child : adjList[node]) {
if (child != parent && depths[child] == -1) { // Ensure the node is unvisited
dfs(child, node, depth + 1, adjList, depths);
}
}
}
int maxDepth(const vector<int>& depths) {
int maxD = 0;
for (int d : depths) {
maxD = max(maxD, d);
}
return maxD;
}
vector<int> updateValues(int i, vector<int>& vals, const vector<int>& depths) {
vector<int> newVals = vals; // Create a copy of vals
for (int j = 0; j < vals.size(); j++) {
if (depths[j] == i) {
newVals[j] *= 2;
} else if (depths[j] == i + 1) {
newVals[j] /= 2;
}
}
return newVals;
}
int main() {
int n;
cin >> n;
// Get initial values of each node
vector<int> vals(n);
for (int i = 0; i < n; i++) {
cin >> vals[i];
}
// Build adjacency list
vector<vector<int>> adjList(n);
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
u--; v--; // Adjust indices to 0-based
adjList[u].push_back(v);
adjList[v].push_back(u);
}
// Calculate the depth of each node using DFS
vector<int> depths(n, -1);
dfs(0, -1, 1, adjList, depths);
// Calculate differences after each operation
vector<long> diffs;
for (int i = 1; i < maxDepth(depths); i++) {
vector<int> tempVals = vals; // Make a temporary copy of vals
vector<int> newVals = updateValues(i, tempVals, depths);
// Calculate the difference
long minVal = numeric_limits<long>::max();
long maxVal = numeric_limits<long>::min();
for (int val : newVals) {
minVal = min(minVal, static_cast<long>(val));
maxVal = max(maxVal, static_cast<long>(val));
}
diffs.push_back(maxVal - minVal);
}
for (size_t i = 0; i < diffs.size(); i++) {
cout << diffs[i];
if (i != diffs.size() - 1) cout << " ";
}
return 0;
}