Description
Solution
对于每一个叶子节点,它到根的路径上存在且仅存在一个点作为最终答案中的叶子节点。
我们从左向右考虑每一条路径,设
d
p
[
u
]
dp[u]
dp[u]表示将路径上的
u
u
u的下面剪掉获得的最大价值。
我们从左向右转移,对于相邻的两个叶子节点,我们只需考虑它们LCA以下的节点。
如果我们对于右边的每一个节点在左边暴力枚举从哪个点转移过来的话,时间复杂度是
O
(
n
2
)
O(n^2)
O(n2)的。
我们可以搞一个前缀后缀最大值就可以优化成
O
(
n
)
O(n)
O(n)了。
Code
/************************************************
* Au: Hany01
* Prob: temmie
* Email: hany01dxx@gmail.com & hany01@foxmail.com
* Inst: Yali High School
************************************************/
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef long double LD;
typedef pair<int, int> PII;
#define rep(i, j) for (register int i = 0, i##_end_ = (j); i < i##_end_; ++ i)
#define For(i, j, k) for (register int i = (j), i##_end_ = (k); i <= i##_end_; ++ i)
#define Fordown(i, j, k) for (register int i = (j), i##_end_ = (k); i >= i##_end_; -- i)
#define Set(a, b) memset(a, b, sizeof(a))
#define Cpy(a, b) memcpy(a, b, sizeof(a))
#define x first
#define y second
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define SZ(a) ((int)(a).size())
#define ALL(a) a.begin(), a.end()
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define y1 wozenmezhemecaia
template <typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
template <typename T> inline bool chkmin(T &a, T b) { return b < a ? a = b, 1 : 0; }
inline int read() {
static int _, __; static char c_;
for (_ = 0, __ = 1, c_ = getchar(); c_ < '0' || c_ > '9'; c_ = getchar()) if (c_ == '-') __ = -1;
for ( ; c_ >= '0' && c_ <= '9'; c_ = getchar()) _ = (_ << 1) + (_ << 3) + (c_ ^ 48);
return _ * __;
}
const int maxn = 1e5 + 5;
int n, w[maxn], ls1[maxn], ls2[maxn], tot1, tot2, maxw[maxn], pre[maxn], suf[maxn], las, top, fa[maxn], dp[maxn], ns[maxn], ans;
vector<int> G[maxn];
void DFS(int u) {
if (!ns[u]) {
if (!las) {
las = u;
for (register int t = u; t != top; t = fa[t]) dp[t] = w[t];
return;
}
tot1 = tot2 = 0;
for (register int t = las; t != top; t = fa[t]) ls1[++ tot1] = t;
for (register int t = u ; t != top; t = fa[t]) ls2[++ tot2] = t;
maxw[tot1 + 1] = 0;
Fordown(i, tot1, 1) maxw[i] = max(maxw[i + 1], w[fa[ls1[i]]]);
suf[tot1 + 1] = -INF;
Fordown(i, tot1, 1) suf[i] = max(suf[i + 1], dp[ls1[i]]);
suf[0] = suf[1];
pre[0] = -INF;
For(i, 1, tot1) pre[i] = max(pre[i - 1], dp[ls1[i]] - maxw[i]);
pre[tot1 + 1] = -INF;
int now = w[top], cur = tot1;
Fordown(i, tot2, 1) {
while (cur && maxw[cur] <= now) -- cur;
dp[ls2[i]] = max(pre[cur], suf[cur + 1] - now) + w[ls2[i]];
chkmax(now, w[ls2[i]]);
}
las = u;
} else rep(i, ns[u]) {
if (i) top = u;
DFS(G[u][i]);
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("temmie.in", "r", stdin);
freopen("temmie.out", "w", stdout);
#endif
n = read();
For(i, 1, n) {
w[i] = read();
rep(j, ns[i] = read()) G[i].pb(read()), fa[G[i][j]] = i;
}
DFS(1), ans = 0;
for (register int t = las; t; t = fa[t]) chkmax(ans, dp[t]);
printf("%d\n", ans);
return 0;
}