游记节选。
P10241 [THUSC 2021] 白兰地厅的西瓜
模板题。
这道题是一道典型的 。而此类题目大都是树形 DP 结合线段树合并来优化。树上路径 LIS,考虑拼接计算贡献。设 表示 子树内以 结尾的最长下降子序列长度, 表示 子树内以 结尾的最长上升子序列长度,设当前枚举到了 的第 个儿子,前面儿子的贡献已经加入到 的 DP 数组中),令 ,则状态转移就很典型了。(不会的可以看一下 的板子,这里不再赘述)
则当前状态对答案的影响为:
单次转移很快,无法继续优化,发现可以将 DP 数组搬到值域线段树上,此时就是一道经典的整体 DP 优化状态转移的题了。
#include<bits/stdc++.h>
#define REP(i, l, r) for (int i = l; i <= r; ++i)
#define PER(i, l, r) for (int i = l; i >= r; --i)
#define ll long long
#define ull unsigned long long
using namespace std;
const int N = 1e5 + 7;
const int V = 1e9;
namespace wyy {
int n, arr[N];
vector<int> NTT[N];
struct seg_tree {
struct Node {
int lc, rc;
int ma;
#define ls(x) tr[x].lc
#define rs(x) tr[x].rc
}tr[N * 80];int Rt[N], trc = 0;
inline void pushup(int x) {
tr[x].ma = max(tr[ls(x)].ma, tr[rs(x)].ma);
}
inline void chkmax(int &x, int l, int r, int now, int c) {
tr[++trc] = tr[x], x = trc;
if (l == r) {
tr[x].ma = max(tr[x].ma, c);
return;
} int mid = (l + r) >> 1;
if (now <= mid) chkmax(ls(x), l, mid, now, c);
else chkmax(rs(x), mid + 1, r, now, c);
pushup(x);
}
inline int askmax(int x, int l, int r, int L, int R) {
if (!x || L > R) return 0;
if (L <= l && r <= R) return tr[x].ma;
int mid = (l + r) >> 1, c = 0;
if (L <= mid) c = askmax(ls(x), l, mid, L, R);
if (mid < R) c = max(c, askmax(rs(x), mid + 1, r, L, R));
return c;
}
inline void merge(int &x, int &y, int l, int r) {
if (!x || !y) {x = x | y; return;}
if (l == r) {
tr[x].ma = max(tr[x].ma, tr[y].ma);
return;
} int mid = (l + r) >> 1;
merge(ls(x), ls(y), l, mid);
merge(rs(x), rs(y), mid + 1, r);
pushup(x);
}
}f, g;
// f : u : 1 2 3 4 5 6 7
// g : u : 7 6 5 4 3 2 1
int Ans = 1;
void chkans(int x, int y, int pmax = 0) {// x -> y
Ans = max(Ans, g.tr[x].ma + pmax);
if (!x || !y) return;
chkans(g.tr[x].lc, f.tr[y].lc, max(pmax, f.tr[f.tr[y].rc].ma));
chkans(g.tr[x].rc, f.tr[y].rc, pmax);
}
void dfs(int x, int fa) {
f.chkmax(f.Rt[x], 1, V, arr[x], 1);
g.chkmax(g.Rt[x], 1, V, arr[x], 1);
for (auto v : NTT[x]) {
if (v == fa) continue;
dfs(v, x);
//用 Rt[v] 贡献和 Rt[x] 贡献拼接得到答案
chkans(g.Rt[x], f.Rt[v]), chkans(g.Rt[v], f.Rt[x]);
f.merge(f.Rt[x], f.Rt[v], 1, V);
g.merge(g.Rt[x], g.Rt[v], 1, V);
int tf = f.askmax(f.Rt[x], 1, V, arr[x] + 1, V) + 1;
f.chkmax(f.Rt[x], 1, V, arr[x], tf);
int tg = g.askmax(g.Rt[x], 1, V, 1, arr[x] - 1) + 1;
g.chkmax(g.Rt[x], 1, V, arr[x], tg);
Ans = max(Ans, max(tf, tg));
}
}
signed main() {
cin >> n; int x, y;
REP(i, 1, n) cin >> arr[i];
REP(i, 1, n) {
cin >> x >> y;
NTT[x].emplace_back(y);
NTT[y].emplace_back(x);
} dfs(1, 0);
cout << Ans << '\n';
return 0;
}
}
signed main() {
// freopen("watermelon.in", "r", stdin);
// freopen("watermelon.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
wyy::main();
return 0;
}