题解:P16145 [ICPC 2017 NAIPC] Heaps from Trees

· · 题解

考虑链上的情况,显然就是求 LIS ,LIS 的标准求法就是线段树优化 dp 以及从前往后扫,用 multiset 维护当前长度为 i 的上升子序列末尾的最小值。

将线段树优化 dp 拍到树上显然就是线段树合并,我没写。

考虑将第二种做法拍到树上。则 multiset 中值的定义转为子树中,转移到 u 时用启发式合并处理子树,并找出第一个大于等于 a_u 的值替换成 a_u,若没有则直接插入 a_u 即可。

最终答案即为根节点的 multiset 的大小。

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<long,long> pii;
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3fll

const int N=2e5+10;

int a[N],n;
multiset<int> st[N];
vector<int> e[N];

void dfs(int u)
{
    for(int v:e[u])
    {
        dfs(v);
        if(st[u].size()<st[v].size()) swap(st[u],st[v]);
        for(int x:st[v]) st[u].insert(x);
    }
    auto tmp=st[u].lower_bound(a[u]);
    if(tmp!=st[u].end()) st[u].erase(tmp);
    st[u].insert(a[u]);
}

inline void solve()
{
    cin >> n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin >> a[i] >> x;
        if(x) e[x].push_back(i);
    }
    dfs(1);
    cout << st[1].size() << '\n';
}

int main()
{
    // int t=clock();
    // freopen("gdx.in","r",stdin);
    // freopen("gdx.out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    // cin >> Type;
    // cin >> T;
    // while(T--)
    solve();
    // cout << clock()-t << '\n';
    return 0;
}