有时间再补,先插眼。
时间复杂度: O ( n ) O(n) O(n)
int n, m;
int h[N], e[N], ne[N], idx;
int s[N];
multiset<int> q[N];
multiset<int> d[N];
int ans;
vector<int> tmp;
int self[N];
int jinian[N];
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a], h[a] = idx++;
}
void dfs1(int u, int fa) {
for (int i = h[u], cnt; ~i; i = ne[i]) {
int j = e[i];
if (j == fa)
continue;
dfs1(j, u);
cnt = s[j];
if (!q[j].empty())
cnt += *(--q[j].end());
q[u].insert(cnt);
if (q[u].size() > 4)
q[u].erase(q[u].begin());
}
}
void dfs2(int u, int fa) {
for (int i = h[u], cnt; ~i; i = ne[i]) {
int j = e[i];
if (j == fa)
continue;
dfs2(j, u);
tmp.clear();
for (auto k : q[j])
tmp.push_back(k);
reverse(all(tmp));
cnt = s[j];
for (int k = 0; k < 2 && k < (int)tmp.size(); k++)
cnt += tmp[k];
self[j] = cnt;
if (!d[j].empty())
self[j] = max(self[j], *(--d[j].end()));
d[u].insert(self[j]);
if (d[u].size() > 2)
d[u].erase(d[u].begin());
}
}
void dfs3(int u, int fa) {
for (int i = h[u], cnt; ~i; i = ne[i]) {
int j = e[i];
if (j == fa)
continue;
cnt = s[j];
if (!q[j].empty())
cnt += *(--q[j].end());
auto t = q[u].find(cnt);
if (t != q[u].end())
q[u].erase(t);
int cha = s[u];
if (!q[u].empty())
cha += *(--q[u].end());
q[j].insert(cha);
if (q[j].size() > 4)
q[j].erase(q[j].begin());
q[u].insert(cnt);
if (q[u].size() > 4)
q[u].erase(q[u].begin());
dfs3(j, u);
jinian[j] = cnt;
}
}
void dfs4(int u, int fa) {
for (int i = h[u], cnt; ~i; i = ne[i]) {
int j = e[i];
if (j == fa)
continue;
dfs4(j, u);
tmp.clear();
for (auto k : q[u])
tmp.push_back(k);
reverse(all(tmp));
cnt = 0;
for (int k = 0; k < 3 && k < (int)tmp.size(); k++)
cnt += tmp[k];
ans = max(ans, cnt + s[u]);
if (tmp.size() == 4)
ans = max(ans, cnt + tmp[3]);
}
}
void dfs5(int u, int fa, int pre) {
for (int i = h[u], cnt; ~i; i = ne[i]) {
int j = e[i];
if (j == fa)
continue;
auto t = d[u].find(self[j]);
if (t != d[u].end())
d[u].erase(t);
cnt = pre;
if (!d[u].empty())
cnt = max(cnt, *(--d[u].end()));
t = q[u].find(jinian[j]);
if (t != q[u].end())
q[u].erase(t);
tmp.clear();
for (auto k : q[u])
tmp.push_back(k);
reverse(all(tmp));
int wu = s[u];
for (int k = 0; k < 2 && k < (int)tmp.size(); k++)
wu += tmp[k];
cnt = max(cnt, wu);
ans = max(ans, cnt + self[j]);
q[u].insert(jinian[j]);
if (q[u].size() > 4)
q[u].erase(q[u].begin());
d[u].insert(self[j]);
if (d[u].size() > 2)
d[u].erase(d[u].begin());
dfs5(j, u, cnt);
}
}
signed main() {
IOS
sf(n);
for (int i = 1; i <= n; i++) {
h[i] = -1;
sf(s[i]);
}
for (int i = 1, a, b; i < n; i++)
sf2(a, b), add(a, b), add(b, a);
if (n == 1) {
pfn(0);
return 0;
}
dfs1(1, 0);
dfs2(1, 0);
dfs3(1, 0);
dfs4(1, 0);
dfs5(1, 0, 0);
pfn(ans);
return 0;
}