BZOJ4919 大根堆 [树上LIS]

大 根 堆 大根堆

题目描述见链接 .


正 解 部 分 \color{red}{正解部分}

树上 L I S LIS LIS 问题,

使用 std::multiset<int> st 维护当前子树内所有可能的 L I S LIS LIS 结尾, 从前往后 L I S LIS LIS结尾 对应的长度递增 .

子树之间互不影响, 只需考虑子树根节点 u u u 对子树内的影响, 类比 序列 L I S LIS LIS 的做法,

  • w u w_u wust中为没有出现过的最大值, 则直接加入 st中 .
  • 否则考虑将 w u w_u wu 作为一个新的可能的 L I S LIS LIS结尾, 替换掉前面某个正好 大于等于 w u w_u wu L I S LIS LIS结尾 . (此时 L I S LIS LIS总长度 并没有变化)

实 现 部 分 \color{red}{实现部分}

#include<bits/stdc++.h>
#define reg register

int read(){
        char c;
        int s = 0, flag = 1;
        while((c=getchar()) && !isdigit(c))
                if(c == '-'){ flag = -1, c = getchar(); break ; }
        while(isdigit(c)) s = s*10 + c-'0', c = getchar();
        return s * flag;
}

const int maxn = 200005;

int N;
int M;
int num0;
int A[maxn];
int head[maxn];

std::multiset <int> st[maxn];
std::multiset <int>::iterator it;

struct Edge{ int nxt, to; } edge[maxn << 1];

void Add(int from, int to){ edge[++ num0] = (Edge){ head[from], to }; head[from] = num0; }

void DFS(int k, int fa){
        for(reg int i = head[k]; i; i = edge[i].nxt){
                int to = edge[i].to;
                if(to == fa) continue ;
                DFS(to, k);
                if(st[to].size() > st[k].size()) std::swap(st[k], st[to]);
                for(it = st[to].begin(); it != st[to].end(); it ++) st[k].insert(*it);
                st[to].clear();
        }
        it = st[k].lower_bound(A[k]);
        if(it != st[k].end()) st[k].erase(it);
        st[k].insert(A[k]);
}

int main(){
        N = read();
        for(reg int i = 1; i <= N; i ++){
                A[i] = read(); int x = read();
                if(!x) continue ;
                Add(x, i), Add(i, x);
        }
        DFS(1, 0); printf("%d\n", st[1].size());
        return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值